level_0
int64
0
10k
index
int64
0
0
repo_id
stringlengths
22
152
file_path
stringlengths
41
203
content
stringlengths
11
11.5M
584
0
petrpan-code/alibaba/hooks/packages/hooks/src/useWhyDidYouUpdate
petrpan-code/alibaba/hooks/packages/hooks/src/useWhyDidYouUpdate/__tests__/index.test.ts
import { renderHook, act } from '@testing-library/react'; import useWhyDidYouUpdate from '../index'; import { useState } from 'react'; describe('useWhyDidYouUpdate', () => { it('should work', () => { console.log = jest.fn(); const setup = () => renderHook(() => { const [count, setCount] = useState(100); useWhyDidYouUpdate('UseWhyDidYouUpdateComponent', { count }); return { setCount, }; }); const hook = setup(); act(() => { hook.result.current.setCount(1); }); expect(console.log).toHaveBeenCalledWith( '[why-did-you-update]', 'UseWhyDidYouUpdateComponent', { count: { from: 100, to: 1, }, }, ); }); });
617
0
petrpan-code/alibaba/hooks/packages/use-url-state/src
petrpan-code/alibaba/hooks/packages/use-url-state/src/__tests__/browser.test.tsx
import { act } from '@testing-library/react'; import { setup } from '.'; describe('useUrlState', () => { it('state should be url search params', () => { const res = setup([ { pathname: '/index', search: '?count=1', }, ]); expect(res.state).toMatchObject({ count: '1' }); }); it('url shoule be changed when use setState', () => { const res = setup(['/index']); expect(res.state).toMatchObject({}); act(() => { res.setState({ count: 1 }); }); expect(res.state).toMatchObject({ count: '1' }); }); it('multiple states should be work', () => { const res = setup(['/index']); act(() => { res.setState({ page: 1 }); }); act(() => { res.setState({ pageSize: 10 }); }); expect(res.state).toMatchObject({ page: '1', pageSize: '10' }); }); it('query-string options should work', async () => { const res = setup( [ { pathname: '/index', search: '?foo=1,2,3', }, ], {}, { parseOptions: { arrayFormat: 'comma', }, stringifyOptions: { arrayFormat: 'comma', }, }, ); expect(res.state).toMatchObject({ foo: ['1', '2', '3'] }); act(() => { res.setState({ foo: ['4', '5', '6'] }); }); expect(res.state).toMatchObject({ foo: ['4', '5', '6'] }); }); it('location.state should be remain', () => { const res = setup([ { pathname: '/index', state: 'state', }, ]); expect(res.location.state).toBe('state'); act(() => { res.setState({ count: 1 }); }); expect(res.state).toMatchObject({ count: '1' }); expect(res.location.state).toBe('state'); }); });
619
0
petrpan-code/alibaba/hooks/packages/use-url-state/src
petrpan-code/alibaba/hooks/packages/use-url-state/src/__tests__/router.test.tsx
import { act } from '@testing-library/react'; import { setup } from '.'; describe('React Router V6', () => { it('useUrlState should be work', () => { const res = setup(['/index']); act(() => { res.setState({ count: 1 }); }); expect(res.state).toMatchObject({ count: '1' }); }); });
2,851
0
petrpan-code/redwoodjs/redwood/__fixtures__/empty-project/api/src/directives
petrpan-code/redwoodjs/redwood/__fixtures__/empty-project/api/src/directives/requireAuth/requireAuth.test.ts
import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' import requireAuth from './requireAuth' describe('requireAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(requireAuth.schema).toBeTruthy() expect(getDirectiveName(requireAuth.schema)).toBe('requireAuth') }) it('requireAuth has stub implementation. Should not throw when current user', () => { // If you want to set values in context, pass it through e.g. // mockRedwoodDirective(requireAuth, { context: { currentUser: { id: 1, name: 'Lebron McGretzky' } }}) const mockExecution = mockRedwoodDirective(requireAuth, { context: {} }) expect(mockExecution).not.toThrowError() }) })
2,853
0
petrpan-code/redwoodjs/redwood/__fixtures__/empty-project/api/src/directives
petrpan-code/redwoodjs/redwood/__fixtures__/empty-project/api/src/directives/skipAuth/skipAuth.test.ts
import { getDirectiveName } from '@redwoodjs/testing/api' import skipAuth from './skipAuth' describe('skipAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(skipAuth.schema).toBeTruthy() expect(getDirectiveName(skipAuth.schema)).toBe('skipAuth') }) })
2,998
0
petrpan-code/redwoodjs/redwood/__fixtures__/fragment-test-project/api/src/directives
petrpan-code/redwoodjs/redwood/__fixtures__/fragment-test-project/api/src/directives/requireAuth/requireAuth.test.ts
import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' import requireAuth from './requireAuth' describe('requireAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(requireAuth.schema).toBeTruthy() expect(getDirectiveName(requireAuth.schema)).toBe('requireAuth') }) it('requireAuth has stub implementation. Should not throw when current user', () => { // If you want to set values in context, pass it through e.g. // mockRedwoodDirective(requireAuth, { context: { currentUser: { id: 1, name: 'Lebron McGretzky' } }}) const mockExecution = mockRedwoodDirective(requireAuth, { context: {} }) expect(mockExecution).not.toThrowError() }) })
3,000
0
petrpan-code/redwoodjs/redwood/__fixtures__/fragment-test-project/api/src/directives
petrpan-code/redwoodjs/redwood/__fixtures__/fragment-test-project/api/src/directives/skipAuth/skipAuth.test.ts
import { getDirectiveName } from '@redwoodjs/testing/api' import skipAuth from './skipAuth' describe('skipAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(skipAuth.schema).toBeTruthy() expect(getDirectiveName(skipAuth.schema)).toBe('skipAuth') }) })
3,057
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project-rsa/api/src/directives
petrpan-code/redwoodjs/redwood/__fixtures__/test-project-rsa/api/src/directives/requireAuth/requireAuth.test.ts
import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' import requireAuth from './requireAuth' describe('requireAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(requireAuth.schema).toBeTruthy() expect(getDirectiveName(requireAuth.schema)).toBe('requireAuth') }) it('requireAuth has stub implementation. Should not throw when current user', () => { // If you want to set values in context, pass it through e.g. // mockRedwoodDirective(requireAuth, { context: { currentUser: { id: 1, name: 'Lebron McGretzky' } }}) const mockExecution = mockRedwoodDirective(requireAuth, { context: {} }) expect(mockExecution).not.toThrowError() }) })
3,059
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project-rsa/api/src/directives
petrpan-code/redwoodjs/redwood/__fixtures__/test-project-rsa/api/src/directives/skipAuth/skipAuth.test.ts
import { getDirectiveName } from '@redwoodjs/testing/api' import skipAuth from './skipAuth' describe('skipAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(skipAuth.schema).toBeTruthy() expect(getDirectiveName(skipAuth.schema)).toBe('skipAuth') }) })
3,111
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project-rsc-external-packages/api/src/directives
petrpan-code/redwoodjs/redwood/__fixtures__/test-project-rsc-external-packages/api/src/directives/requireAuth/requireAuth.test.ts
import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' import requireAuth from './requireAuth' describe('requireAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(requireAuth.schema).toBeTruthy() expect(getDirectiveName(requireAuth.schema)).toBe('requireAuth') }) it('requireAuth has stub implementation. Should not throw when current user', () => { // If you want to set values in context, pass it through e.g. // mockRedwoodDirective(requireAuth, { context: { currentUser: { id: 1, name: 'Lebron McGretzky' } }}) const mockExecution = mockRedwoodDirective(requireAuth, { context: {} }) expect(mockExecution).not.toThrowError() }) })
3,113
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project-rsc-external-packages/api/src/directives
petrpan-code/redwoodjs/redwood/__fixtures__/test-project-rsc-external-packages/api/src/directives/skipAuth/skipAuth.test.ts
import { getDirectiveName } from '@redwoodjs/testing/api' import skipAuth from './skipAuth' describe('skipAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(skipAuth.schema).toBeTruthy() expect(getDirectiveName(skipAuth.schema)).toBe('skipAuth') }) })
3,167
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/__tests__/context.test.ts
test('Set a mock user on the context', async () => { const user = { id: 0o7, name: 'Bond, James Bond', email: '[email protected]', roles: 'secret_agent', } mockCurrentUser(user) expect(context.currentUser).toStrictEqual(user) }) test('Context is isolated between tests', () => { expect(context).toStrictEqual({ currentUser: undefined }) })
3,168
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/directives
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/directives/requireAuth/requireAuth.test.ts
import { mockRedwoodDirective, getDirectiveName } from '@redwoodjs/testing/api' import requireAuth from './requireAuth' describe('requireAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(requireAuth.schema).toBeTruthy() expect(getDirectiveName(requireAuth.schema)).toBe('requireAuth') }) it('requireAuth has stub implementation. Should not throw when current user', () => { // If you want to set values in context, pass it through e.g. // mockRedwoodDirective(requireAuth, { context: { currentUser: { id: 1, name: 'Lebron McGretzky' } }}) const mockExecution = mockRedwoodDirective(requireAuth, { context: { currentUser: { id: 1, roles: 'ADMIN', email: '[email protected]' } }, }) expect(mockExecution).not.toThrowError() }) })
3,170
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/directives
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/directives/skipAuth/skipAuth.test.ts
import { getDirectiveName } from '@redwoodjs/testing/api' import skipAuth from './skipAuth' describe('skipAuth directive', () => { it('declares the directive sdl as schema, with the correct name', () => { expect(skipAuth.schema).toBeTruthy() expect(getDirectiveName(skipAuth.schema)).toBe('skipAuth') }) })
3,181
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/services
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/services/contacts/contacts.test.ts
import type { Contact } from '@prisma/client' import { contacts, contact, createContact, updateContact, deleteContact, } from './contacts' import type { StandardScenario } from './contacts.scenarios' // Generated boilerplate tests do not account for all circumstances // and can fail without adjustments, e.g. Float. // Please refer to the RedwoodJS Testing Docs: // https://redwoodjs.com/docs/testing#testing-services // https://redwoodjs.com/docs/testing#jest-expect-type-considerations describe('contacts', () => { scenario('returns all contacts', async (scenario: StandardScenario) => { const result = await contacts() expect(result.length).toEqual(Object.keys(scenario.contact).length) }) scenario('returns a single contact', async (scenario: StandardScenario) => { const result = await contact({ id: scenario.contact.one.id }) expect(result).toEqual(scenario.contact.one) }) scenario('creates a contact', async () => { const result = await createContact({ input: { name: 'String', email: 'String', message: 'String' }, }) expect(result.name).toEqual('String') expect(result.email).toEqual('String') expect(result.message).toEqual('String') }) scenario('updates a contact', async (scenario: StandardScenario) => { const original = (await contact({ id: scenario.contact.one.id })) as Contact const result = await updateContact({ id: original.id, input: { name: 'String2' }, }) expect(result.name).toEqual('String2') }) scenario('deletes a contact', async (scenario: StandardScenario) => { const original = (await deleteContact({ id: scenario.contact.one.id, })) as Contact const result = await contact({ id: original.id }) expect(result).toEqual(null) }) })
3,184
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/services
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/services/posts/posts.test.ts
import type { Post } from '@prisma/client' import { posts, post, createPost, updatePost, deletePost } from './posts' import type { StandardScenario } from './posts.scenarios' // Generated boilerplate tests do not account for all circumstances // and can fail without adjustments, e.g. Float. // Please refer to the RedwoodJS Testing Docs: // https://redwoodjs.com/docs/testing#testing-services // https://redwoodjs.com/docs/testing#jest-expect-type-considerations describe('posts', () => { scenario('returns all posts', async (scenario: StandardScenario) => { const result = await posts() expect(result.length).toEqual(Object.keys(scenario.post).length) }) scenario('returns a single post', async (scenario: StandardScenario) => { const result = await post({ id: scenario.post.one.id }) expect(result).toEqual(scenario.post.one) }) scenario('creates a post', async (scenario: StandardScenario) => { const result = await createPost({ input: { title: 'String', body: 'String', authorId: scenario.post.two.authorId, }, }) expect(result.title).toEqual('String') expect(result.body).toEqual('String') expect(result.authorId).toEqual(scenario.post.two.authorId) }) scenario('updates a post', async (scenario: StandardScenario) => { const original = (await post({ id: scenario.post.one.id })) as Post const result = await updatePost({ id: original.id, input: { title: 'String2' }, }) expect(result.title).toEqual('String2') }) scenario('deletes a post', async (scenario: StandardScenario) => { const original = (await deletePost({ id: scenario.post.one.id })) as Post const result = await post({ id: original.id }) expect(result).toEqual(null) }) })
3,187
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/services
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/api/src/services/users/users.test.ts
import { user } from './users' import type { StandardScenario } from './users.scenarios' describe('users', () => { scenario('returns a single user', async (scenario: StandardScenario) => { const result = await user({ id: scenario.user.one.id }) expect(result).toEqual(scenario.user.one) }) })
3,208
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components/Author/Author.test.tsx
import { render } from '@redwoodjs/testing/web' import Author from './Author' const author = { email: '[email protected]', fullName: 'Test User', } // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-components describe('Author', () => { it('renders successfully', () => { expect(() => { render(<Author author={author} />) }).not.toThrow() }) })
3,212
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components/AuthorCell/AuthorCell.test.tsx
import { render } from '@redwoodjs/testing/web' import { Loading, Empty, Failure, Success } from './AuthorCell' import { standard } from './AuthorCell.mock' // Generated boilerplate tests do not account for all circumstances // and can fail without adjustments, e.g. Float and DateTime types. // Please refer to the RedwoodJS Testing Docs: // https://redwoodjs.com/docs/testing#testing-cells // https://redwoodjs.com/docs/testing#jest-expect-type-considerations describe('AuthorCell', () => { it('renders Loading successfully', () => { expect(() => { render(<Loading />) }).not.toThrow() }) it('renders Empty successfully', async () => { expect(() => { render(<Empty />) }).not.toThrow() }) it('renders Failure successfully', async () => { expect(() => { render(<Failure error={new Error('Oh no')} />) }).not.toThrow() }) // When you're ready to test the actual output of your component render // you could test that, for example, certain text is present: // // 1. import { screen } from '@redwoodjs/testing/web' // 2. Add test: expect(screen.getByText('Hello, world')).toBeInTheDocument() it('renders Success successfully', async () => { expect(() => { render(<Success author={standard().author} />) }).not.toThrow() }) })
3,215
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components/BlogPost/BlogPost.test.tsx
import { render } from '@redwoodjs/testing/web' import BlogPost from './BlogPost' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-components describe('BlogPost', () => { it('renders successfully', () => { expect(() => { render(<BlogPost />) }).not.toThrow() }) })
3,219
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components/BlogPostCell/BlogPostCell.test.tsx
import { render } from '@redwoodjs/testing/web' import { Loading, Empty, Failure, Success } from './BlogPostCell' import { standard } from './BlogPostCell.mock' // Generated boilerplate tests do not account for all circumstances // and can fail without adjustments, e.g. Float and DateTime types. // Please refer to the RedwoodJS Testing Docs: // https://redwoodjs.com/docs/testing#testing-cells // https://redwoodjs.com/docs/testing#jest-expect-type-considerations describe('BlogPostCell', () => { it('renders Loading successfully', () => { expect(() => { render(<Loading />) }).not.toThrow() }) it('renders Empty successfully', async () => { expect(() => { render(<Empty />) }).not.toThrow() }) it('renders Failure successfully', async () => { expect(() => { render(<Failure error={new Error('Oh no')} />) }).not.toThrow() }) // When you're ready to test the actual output of your component render // you could test that, for example, certain text is present: // // 1. import { screen } from '@redwoodjs/testing/web' // 2. Add test: expect(screen.getByText('Hello, world')).toBeInTheDocument() it('renders Success successfully', async () => { expect(() => { render(<Success blogPost={standard().blogPost} />) }).not.toThrow() }) })
3,223
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components/BlogPostsCell/BlogPostsCell.test.tsx
import { render } from '@redwoodjs/testing/web' import { Loading, Empty, Failure, Success } from './BlogPostsCell' import { standard } from './BlogPostsCell.mock' // Generated boilerplate tests do not account for all circumstances // and can fail without adjustments, e.g. Float and DateTime types. // Please refer to the RedwoodJS Testing Docs: // https://redwoodjs.com/docs/testing#testing-cells // https://redwoodjs.com/docs/testing#jest-expect-type-considerations describe('BlogPostsCell', () => { it('renders Loading successfully', () => { expect(() => { render(<Loading />) }).not.toThrow() }) it('renders Empty successfully', async () => { expect(() => { render(<Empty />) }).not.toThrow() }) it('renders Failure successfully', async () => { expect(() => { render(<Failure error={new Error('Oh no')} />) }).not.toThrow() }) // When you're ready to test the actual output of your component render // you could test that, for example, certain text is present: // // 1. import { screen } from '@redwoodjs/testing/web' // 2. Add test: expect(screen.getByText('Hello, world')).toBeInTheDocument() it('renders Success successfully', async () => { expect(() => { render(<Success blogPosts={standard().blogPosts} />) }).not.toThrow() }) })
3,241
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/components/WaterfallBlogPostCell/WaterfallBlogPostCell.test.tsx
import { render } from '@redwoodjs/testing/web' import { Loading, Empty, Failure, Success } from './WaterfallBlogPostCell' import { standard } from './WaterfallBlogPostCell.mock' // Generated boilerplate tests do not account for all circumstances // and can fail without adjustments, e.g. Float and DateTime types. // Please refer to the RedwoodJS Testing Docs: // https://redwoodjs.com/docs/testing#testing-cells // https://redwoodjs.com/docs/testing#jest-expect-type-considerations describe('WaterfallBlogPostCell', () => { it('renders Loading successfully', () => { expect(() => { render(<Loading />) }).not.toThrow() }) it('renders Empty successfully', async () => { expect(() => { render(<Empty />) }).not.toThrow() }) it('renders Failure successfully', async () => { expect(() => { render(<Failure error={new Error('Oh no')} />) }).not.toThrow() }) // When you're ready to test the actual output of your component render // you could test that, for example, certain text is present: // // 1. import { screen } from '@redwoodjs/testing/web' // 2. Add test: expect(screen.getByText('Hello, world')).toBeInTheDocument() it('renders Success successfully', async () => { expect(() => { render(<Success waterfallBlogPost={standard().waterfallBlogPost} />) }).not.toThrow() }) })
3,244
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/layouts
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/layouts/BlogLayout/BlogLayout.test.tsx
import { render } from '@redwoodjs/testing/web' import BlogLayout from './BlogLayout' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('BlogLayout', () => { it('renders successfully', () => { expect(() => { render(<BlogLayout />) }).not.toThrow() }) })
3,247
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/lib/formatters.test.tsx
import { render, waitFor, screen } from '@redwoodjs/testing/web' import { formatEnum, jsonTruncate, truncate, timeTag, jsonDisplay, checkboxInputTag, } from './formatters' describe('formatEnum', () => { it('handles nullish values', () => { expect(formatEnum(null)).toEqual('') expect(formatEnum('')).toEqual('') expect(formatEnum(undefined)).toEqual('') }) it('formats a list of values', () => { expect( formatEnum(['RED', 'ORANGE', 'YELLOW', 'GREEN', 'BLUE', 'VIOLET']) ).toEqual('Red, Orange, Yellow, Green, Blue, Violet') }) it('formats a single value', () => { expect(formatEnum('DARK_BLUE')).toEqual('Dark blue') }) it('returns an empty string for values of the wrong type (for JS projects)', () => { // @ts-expect-error - Testing JS scenario expect(formatEnum(5)).toEqual('') }) }) describe('truncate', () => { it('truncates really long strings', () => { expect(truncate('na '.repeat(1000) + 'batman').length).toBeLessThan(1000) expect(truncate('na '.repeat(1000) + 'batman')).not.toMatch(/batman/) }) it('does not modify short strings', () => { expect(truncate('Short strinG')).toEqual('Short strinG') }) it('adds ... to the end of truncated strings', () => { expect(truncate('repeat'.repeat(1000))).toMatch(/\w\.\.\.$/) }) it('accepts numbers', () => { expect(truncate(123)).toEqual('123') expect(truncate(0)).toEqual('0') expect(truncate(0o000)).toEqual('0') }) it('handles arguments of invalid type', () => { // @ts-expect-error - Testing JS scenario expect(truncate(false)).toEqual('false') expect(truncate(undefined)).toEqual('') expect(truncate(null)).toEqual('') }) }) describe('jsonTruncate', () => { it('truncates large json structures', () => { expect( jsonTruncate({ foo: 'foo', bar: 'bar', baz: 'baz', kittens: 'kittens meow', bazinga: 'Sheldon', nested: { foobar: 'I have no imagination', two: 'Second nested item', }, five: 5, bool: false, }) ).toMatch(/.+\n.+\w\.\.\.$/s) }) }) describe('timeTag', () => { it('renders a date', async () => { render(<div>{timeTag(new Date('1970-08-20').toUTCString())}</div>) await waitFor(() => screen.getByText(/1970.*00:00:00/)) }) it('can take an empty input string', async () => { expect(timeTag('')).toEqual('') }) }) describe('jsonDisplay', () => { it('produces the correct output', () => { expect( jsonDisplay({ title: 'TOML Example (but in JSON)', database: { data: [['delta', 'phi'], [3.14]], enabled: true, ports: [8000, 8001, 8002], temp_targets: { case: 72.0, cpu: 79.5, }, }, owner: { dob: '1979-05-27T07:32:00-08:00', name: 'Tom Preston-Werner', }, servers: { alpha: { ip: '10.0.0.1', role: 'frontend', }, beta: { ip: '10.0.0.2', role: 'backend', }, }, }) ).toMatchInlineSnapshot(` <pre> <code> { "title": "TOML Example (but in JSON)", "database": { "data": [ [ "delta", "phi" ], [ 3.14 ] ], "enabled": true, "ports": [ 8000, 8001, 8002 ], "temp_targets": { "case": 72, "cpu": 79.5 } }, "owner": { "dob": "1979-05-27T07:32:00-08:00", "name": "Tom Preston-Werner" }, "servers": { "alpha": { "ip": "10.0.0.1", "role": "frontend" }, "beta": { "ip": "10.0.0.2", "role": "backend" } } } </code> </pre> `) }) }) describe('checkboxInputTag', () => { it('can be checked', () => { render(checkboxInputTag(true)) expect(screen.getByRole('checkbox')).toBeChecked() }) it('can be unchecked', () => { render(checkboxInputTag(false)) expect(screen.getByRole('checkbox')).not.toBeChecked() }) it('is disabled when checked', () => { render(checkboxInputTag(true)) expect(screen.getByRole('checkbox')).toBeDisabled() }) it('is disabled when unchecked', () => { render(checkboxInputTag(false)) expect(screen.getByRole('checkbox')).toBeDisabled() }) })
3,250
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages/AboutPage/AboutPage.test.tsx
import { render } from '@redwoodjs/testing/web' import AboutPage from './AboutPage' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('AboutPage', () => { it('renders successfully', () => { expect(() => { render(<AboutPage />) }).not.toThrow() }) })
3,254
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages/BlogPostPage/BlogPostPage.test.tsx
import { render } from '@redwoodjs/testing/web' import BlogPostPage from './BlogPostPage' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('BlogPostPage', () => { it('renders successfully', () => { expect(() => { render(<BlogPostPage id={42} />) }).not.toThrow() }) })
3,261
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages/ContactUsPage/ContactUsPage.test.tsx
import { render } from '@redwoodjs/testing/web' import ContactUsPage from './ContactUsPage' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('ContactUsPage', () => { it('renders successfully', () => { expect(() => { render(<ContactUsPage />) }).not.toThrow() }) })
3,264
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages/DoublePage/DoublePage.test.tsx
import { render } from '@redwoodjs/testing/web' import DoublePage from './DoublePage' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('DoublePage', () => { it('renders successfully', () => { expect(() => { render(<DoublePage />) }).not.toThrow() }) })
3,269
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages/HomePage/HomePage.test.tsx
import { render } from '@redwoodjs/testing/web' import HomePage from './HomePage' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('HomePage', () => { it('renders successfully', () => { expect(() => { render(<HomePage />) }).not.toThrow() }) })
3,278
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages/ProfilePage/ProfilePage.test.tsx
import { render, waitFor, screen } from '@redwoodjs/testing/web' import ProfilePage from './ProfilePage' describe('ProfilePage', () => { it('renders successfully', async () => { mockCurrentUser({ email: '[email protected]', id: 84849020, roles: 'BAZINGA', }) await waitFor(async () => { expect(() => { render(<ProfilePage />) }).not.toThrow() }) expect(await screen.findByText('[email protected]')).toBeInTheDocument() }) })
3,284
0
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages
petrpan-code/redwoodjs/redwood/__fixtures__/test-project/web/src/pages/WaterfallPage/WaterfallPage.test.tsx
import { render } from '@redwoodjs/testing/web' import WaterfallPage from './WaterfallPage' // Improve this test with help from the Redwood Testing Doc: // https://redwoodjs.com/docs/testing#testing-pages-layouts describe('WaterfallPage', () => { it('renders successfully', () => { expect(() => { render(<WaterfallPage id={42} />) }).not.toThrow() }) })
4,033
0
petrpan-code/redwoodjs/redwood/packages
petrpan-code/redwoodjs/redwood/packages/api-server/dist.test.ts
import fs from 'fs' import path from 'path' const distPath = path.join(__dirname, 'dist') const packageConfig = JSON.parse(fs.readFileSync('./package.json', 'utf-8')) describe('dist', () => { it("shouldn't have the __tests__ directory", () => { expect(fs.existsSync(path.join(distPath, '__tests__'))).toEqual(false) }) // The way this package was written, you can't just import it. It expects to be in a Redwood project. it('fails if imported outside a Redwood app', async () => { try { await import(path.join(distPath, 'cliHandlers.js')) } catch (e) { expect(e.message).toMatchInlineSnapshot( `"Could not find a "redwood.toml" file, are you sure you're in a Redwood project?"` ) } }) it('exports CLI options and handlers', async () => { const original_RWJS_CWD = process.env.RWJS_CWD process.env.RWJS_CWD = path.join( __dirname, 'src/__tests__/fixtures/redwood-app' ) const mod = await import( path.resolve(distPath, packageConfig.main.replace('dist/', '')) ) expect(mod).toMatchInlineSnapshot(` { "apiCliOptions": { "apiRootPath": { "alias": [ "rootPath", "root-path", ], "coerce": [Function], "default": "/", "desc": "Root path where your api functions are served", "type": "string", }, "loadEnvFiles": { "default": false, "description": "Load .env and .env.defaults files", "type": "boolean", }, "port": { "alias": "p", "default": 8911, "type": "number", }, "socket": { "type": "string", }, }, "apiServerHandler": [Function], "bothServerHandler": [Function], "commonOptions": { "port": { "alias": "p", "default": 8910, "type": "number", }, "socket": { "type": "string", }, }, "webCliOptions": { "apiHost": { "alias": "api-host", "desc": "Forward requests from the apiUrl, defined in redwood.toml to this host", "type": "string", }, "port": { "alias": "p", "default": 8910, "type": "number", }, "socket": { "type": "string", }, }, "webServerHandler": [Function], } `) process.env.RWJS_CWD = original_RWJS_CWD }) it('ships three bins', () => { expect(packageConfig.bin).toMatchInlineSnapshot(` { "rw-api-server-watch": "./dist/watch.js", "rw-log-formatter": "./dist/logFormatter/bin.js", "rw-server": "./dist/index.js", } `) }) })
4,043
0
petrpan-code/redwoodjs/redwood/packages/api-server/src
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/fastify.test.ts
import fastify from 'fastify' import { vol } from 'memfs' import { createFastifyInstance, DEFAULT_OPTIONS } from '../fastify' // We'll be testing how fastify is instantiated, so we'll mock it here. jest.mock('fastify', () => { return jest.fn(() => { return { register: () => {}, } }) }) // Suppress terminal logging. console.log = jest.fn() // Set up RWJS_CWD. let original_RWJS_CWD const FIXTURE_PATH = '/redwood-app' beforeAll(() => { original_RWJS_CWD = process.env.RWJS_CWD process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { process.env.RWJS_CWD = original_RWJS_CWD }) // Mock server.config.js to test instantiating fastify with user config. jest.mock('fs', () => require('memfs').fs) afterEach(() => { vol.reset() }) const userConfig = { requestTimeout: 25_000, } jest.mock( '/redwood-app/api/server.config.js', () => { return { config: userConfig, } }, { virtual: true, } ) jest.mock( '\\redwood-app\\api\\server.config.js', () => { return { config: userConfig, } }, { virtual: true, } ) describe('createFastifyInstance', () => { it('instantiates a fastify instance with default config', () => { vol.fromNestedJSON( { 'redwood.toml': '', }, FIXTURE_PATH ) createFastifyInstance() expect(fastify).toHaveBeenCalledWith(DEFAULT_OPTIONS) }) it("instantiates a fastify instance with the user's configuration if available", () => { vol.fromNestedJSON( { 'redwood.toml': '', api: { 'server.config.js': '', }, }, FIXTURE_PATH ) createFastifyInstance() expect(fastify).toHaveBeenCalledWith(userConfig) }) }) test('DEFAULT_OPTIONS configures the log level based on NODE_ENV', () => { expect(DEFAULT_OPTIONS).toMatchInlineSnapshot(` { "logger": { "level": "info", }, } `) })
4,044
0
petrpan-code/redwoodjs/redwood/packages/api-server/src
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/lambdaLoader.test.ts
import path from 'path' import { LAMBDA_FUNCTIONS, loadFunctionsFromDist, } from '../plugins/lambdaLoader' // Suppress terminal logging. console.log = jest.fn() console.warn = jest.fn() // Set up RWJS_CWD. let original_RWJS_CWD beforeAll(() => { original_RWJS_CWD = process.env.RWJS_CWD process.env.RWJS_CWD = path.resolve(__dirname, 'fixtures/redwood-app') }) afterAll(() => { process.env.RWJS_CWD = original_RWJS_CWD }) // Reset the LAMBDA_FUNCTIONS object after each test. afterEach(() => { for (const key in LAMBDA_FUNCTIONS) { delete LAMBDA_FUNCTIONS[key] } }) describe('loadFunctionsFromDist', () => { it('loads functions from the api/dist directory', async () => { expect(LAMBDA_FUNCTIONS).toEqual({}) await loadFunctionsFromDist() expect(LAMBDA_FUNCTIONS).toEqual({ env: expect.any(Function), graphql: expect.any(Function), health: expect.any(Function), hello: expect.any(Function), nested: expect.any(Function), }) }) // We have logic that specifically puts the graphql function at the front. // Though it's not clear why or if this is actually respected by how JS objects work. // See the complementary lambdaLoaderNumberFunctions test. it('puts the graphql function first', async () => { expect(LAMBDA_FUNCTIONS).toEqual({}) await loadFunctionsFromDist() expect(Object.keys(LAMBDA_FUNCTIONS)[0]).toEqual('graphql') }) // `loadFunctionsFromDist` loads files that don't export a handler into the object as `undefined`. // This is probably harmless, but we could also probably go without it. it("warns if a function doesn't have a handler and sets it to `undefined`", async () => { expect(LAMBDA_FUNCTIONS).toEqual({}) await loadFunctionsFromDist() expect(LAMBDA_FUNCTIONS).toMatchObject({ noHandler: undefined, }) expect(console.warn).toHaveBeenCalledWith( 'noHandler', 'at', expect.any(String), 'does not have a function called handler defined.' ) }) })
4,045
0
petrpan-code/redwoodjs/redwood/packages/api-server/src
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/lambdaLoaderNumberFunctions.test.ts
import path from 'path' import { LAMBDA_FUNCTIONS, loadFunctionsFromDist, } from '../plugins/lambdaLoader' // Suppress terminal logging. console.log = jest.fn() // Set up RWJS_CWD. let original_RWJS_CWD beforeAll(() => { original_RWJS_CWD = process.env.RWJS_CWD process.env.RWJS_CWD = path.resolve( __dirname, 'fixtures/redwood-app-number-functions' ) }) afterAll(() => { process.env.RWJS_CWD = original_RWJS_CWD }) test('loadFunctionsFromDist puts functions named with numbers before the graphql function', async () => { expect(LAMBDA_FUNCTIONS).toEqual({}) await loadFunctionsFromDist() expect(Object.keys(LAMBDA_FUNCTIONS)[0]).toEqual('1') })
4,046
0
petrpan-code/redwoodjs/redwood/packages/api-server/src
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/logFormatter.test.ts
import { LogFormatter } from '../logFormatter/index' const logFormatter = LogFormatter() describe('LogFormatter', () => { describe('Formats log levels as emoji', () => { it('Formats Trace level', () => { expect(logFormatter({ level: 10 })).toMatch('🧡') }) it('Formats Debug level', () => { expect(logFormatter({ level: 20 })).toMatch('πŸ›') }) it('Formats Info level', () => { expect(logFormatter({ level: 30 })).toMatch('🌲') }) it('Formats Warn level', () => { expect(logFormatter({ level: 40 })).toMatch('🚦') }) it('Formats Error level', () => { expect(logFormatter({ level: 50 })).toMatch('🚨') }) }) describe('Formats log messages', () => { it('Formats newline-delimited json data with a message', () => { expect( logFormatter({ level: 10, message: 'Message in a bottle' }) ).toMatch('Message in a bottle') }) it('Formats newline-delimited json data with a msg', () => { expect(logFormatter({ level: 10, msg: 'Message in a bottle' })).toMatch( 'Message in a bottle' ) }) it('Formats a text message', () => { expect(logFormatter('Handles text data')).toMatch('Handles text data') }) it('Formats Get Method and Status Code', () => { const logData = { level: 10, method: 'GET', statusCode: 200 } expect(logFormatter(logData)).toMatch('GET') expect(logFormatter(logData)).toMatch('200') }) it('Formats Post Method and Status Code', () => { const logData = { level: 10, method: 'POST', statusCode: 200 } expect(logFormatter(logData)).toMatch('POST') expect(logFormatter(logData)).toMatch('200') }) it('Should not format Status Code without a Method', () => { expect(logFormatter({ level: 10, statusCode: 200 })).not.toMatch('200') }) }) describe('Formats GraphQL injected log data from useRedwoodLogger plugin', () => { it('Handles query', () => { expect( logFormatter({ level: 10, query: { id: 1, }, }) ).toMatch('"id": 1') }) it('Handles operation name', () => { expect( logFormatter({ level: 10, operationName: 'GET_BLOG_POST_BY_ID' }) ).toMatch('GET_BLOG_POST_BY_ID') }) it('Handles GraphQL data', () => { expect( logFormatter({ level: 10, data: { post: { id: 1, title: 'My Blog Post' } }, }) ).toMatch('My Blog Post') }) it('Handles browser user agent', () => { const userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15' expect( logFormatter({ level: 10, userAgent, }) ).toMatch(/Mozilla.*AppleWebKit.*Safari/) }) }) describe('Custom log data', () => { it('Should include the custom log attribute text', () => { expect( logFormatter({ level: 10, custom: 'I should see this custom message text', }) ).toMatch('I should see this') }) it('Should include the custom log attribute info a custom emoji and label', () => { expect( logFormatter({ level: 10, custom: 'I should see this custom emoji and label', }) ).toMatch('πŸ—’ Custom') }) it('Should include the custom log attribute info with nested text message', () => { expect( logFormatter({ level: 10, custom: { string: 'I should see this custom message in the log', }, }) ).toMatch('I should see this custom message in the log') }) it('Should include the custom log attribute info with a number attribute', () => { expect( logFormatter({ level: 10, custom: { string: 'I should see this custom message and number in the log', number: 100, }, }) ).toMatch('100') }) it('Should include the custom log attribute info with a nested object attribute', () => { expect( logFormatter({ level: 10, custom: { string: 'I should see this custom object in the log', obj: { foo: 'bar' }, }, }) ).toMatch('"foo": "bar"') }) it('Should include the custom log attribute info with a nested object attribute', () => { expect( logFormatter({ level: 10, custom: { string: 'I should see this custom object in the log', obj: { foo: 'bar' }, }, }) ).toMatch('"foo": "bar"') }) it('Should filter out overly verbose custom log attributes', () => { expect( logFormatter({ level: 10, custom: { time: 1, pid: 1, hostname: 'should not appear', reqId: 'should not appear', req: { method: 'should not appear', url: 'should not appear', hostname: 'should not appear', remoteAddress: 'should not appear', remotePort: 1, }, }, }) ).not.toMatch('should not appear') }) }) it('Should format error stack traces', () => { expect( logFormatter({ level: 50, err: { message: 'This error has a stack traces', stack: 'A stack trace \n will have \n several lines \n at some line number \n at some code', }, }) ).toMatch(/at some line number/) }) it('Should format error and include the error type', () => { expect( logFormatter({ level: 50, err: { type: 'GraphQL Error', message: 'This error has a stack traces', stack: 'A stack trace \n will have \n several lines \n at some line number \n at some code', }, }) ).toMatch(/GraphQL Error Info/) }) describe('When there are additional options', () => { it('Should format and include additional options without custom tag', () => { expect( logFormatter({ level: 10, apiVersion: '4.2.1', environment: 'staging', }) ).toMatch('"apiVersion": "4.2.1"') expect( logFormatter({ level: 10, apiVersion: '4.2.1', environment: 'staging', }) ).toMatch('"environment": "staging"') }) it('Should format and include additional nested options without custom tag', () => { expect( logFormatter({ level: 10, deploy: { environment: 'staging', version: '4.2.1', }, }) ).toMatch('"deploy"') expect( logFormatter({ level: 10, deploy: { environment: 'staging', version: '4.2.1', }, }) ).toMatch('"environment": "staging"') logFormatter({ level: 10, deploy: { environment: 'staging', version: '4.2.1', }, }) // ? expect( logFormatter({ level: 10, deploy: { environment: 'staging', version: '4.2.1', }, }) ).toMatch('"version": "4.2.1"') }) }) it('Should not have any undefined ns, name, or message', () => { expect( logFormatter({ level: 10, }) ).not.toContain('undefined') }) })
4,047
0
petrpan-code/redwoodjs/redwood/packages/api-server/src
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/withApiProxy.test.ts
import httpProxy from '@fastify/http-proxy' import type { FastifyInstance } from 'fastify' import withApiProxy from '../plugins/withApiProxy' test('withApiProxy registers `@fastify/http-proxy`', async () => { const mockedFastifyInstance = { register: jest.fn(), } // `apiUrl` is unfortunately named. It isn't a URL, it's just a prefix. Meanwhile, `apiHost` _is_ a URL. // See https://github.com/fastify/fastify-http-proxy and https://github.com/fastify/fastify-reply-from. await withApiProxy(mockedFastifyInstance as unknown as FastifyInstance, { apiUrl: 'my-api-host', apiHost: 'http://localhost:8910', }) expect(mockedFastifyInstance.register).toHaveBeenCalledWith(httpProxy, { disableCache: true, prefix: 'my-api-host', upstream: 'http://localhost:8910', }) })
4,048
0
petrpan-code/redwoodjs/redwood/packages/api-server/src
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/withFunctions.test.ts
import path from 'path' import createFastifyInstance from '../fastify' import withFunctions from '../plugins/withFunctions' // Suppress terminal logging. console.log = jest.fn() console.warn = jest.fn() // Set up RWJS_CWD. let original_RWJS_CWD beforeAll(() => { original_RWJS_CWD = process.env.RWJS_CWD process.env.RWJS_CWD = path.resolve(__dirname, 'fixtures/redwood-app') }) afterAll(() => { process.env.RWJS_CWD = original_RWJS_CWD }) // Set up and teardown the fastify instance for each test. let fastifyInstance let returnedFastifyInstance beforeAll(async () => { fastifyInstance = createFastifyInstance() returnedFastifyInstance = await withFunctions(fastifyInstance, { port: 8911, apiRootPath: '/', }) await fastifyInstance.ready() }) afterAll(async () => { await fastifyInstance.close() }) describe('withFunctions', () => { // Deliberately using `toBe` here to check for referential equality. it('returns the same fastify instance', async () => { expect(returnedFastifyInstance).toBe(fastifyInstance) }) it('configures the `@fastify/url-data` and `fastify-raw-body` plugins', async () => { const plugins = fastifyInstance.printPlugins() expect(plugins.includes('@fastify/url-data')).toEqual(true) expect(plugins.includes('fastify-raw-body')).toEqual(true) }) it('configures two additional content type parsers, `application/x-www-form-urlencoded` and `multipart/form-data`', async () => { expect( fastifyInstance.hasContentTypeParser('application/x-www-form-urlencoded') ).toEqual(true) expect(fastifyInstance.hasContentTypeParser('multipart/form-data')).toEqual( true ) }) it('can be configured by the user', async () => { const res = await fastifyInstance.inject({ method: 'GET', url: '/rest/v1/users/get/1', }) expect(res.body).toEqual(JSON.stringify({ id: 1 })) }) // We use `fastify.all` to register functions, which means they're invoked for all HTTP verbs. // Only testing GET and POST here at the moment. // // We can use `printRoutes` with a method for debugging, but not without one. // See https://fastify.dev/docs/latest/Reference/Server#printroutes it('builds a tree of routes for GET and POST', async () => { expect(fastifyInstance.printRoutes({ method: 'GET' })) .toMatchInlineSnapshot(` "└── / β”œβ”€β”€ rest/v1/users/get/ β”‚ └── :userId (GET) └── :routeName (GET) └── / └── * (GET) " `) expect(fastifyInstance.printRoutes({ method: 'POST' })) .toMatchInlineSnapshot(` "└── / └── :routeName (POST) └── / └── * (POST) " `) }) describe('serves functions', () => { it('serves hello.js', async () => { const res = await fastifyInstance.inject({ method: 'GET', url: '/hello', }) expect(res.statusCode).toEqual(200) expect(res.json()).toEqual({ data: 'hello function' }) }) it('it serves graphql.js', async () => { const res = await fastifyInstance.inject({ method: 'POST', url: '/graphql?query={redwood{version}}', }) expect(res.statusCode).toEqual(200) expect(res.json()).toEqual({ data: { version: 42 } }) }) it('serves health.js', async () => { const res = await fastifyInstance.inject({ method: 'GET', url: '/health', }) expect(res.statusCode).toEqual(200) }) it('serves a nested function, nested.js', async () => { const res = await fastifyInstance.inject({ method: 'GET', url: '/nested/nested', }) expect(res.statusCode).toEqual(200) expect(res.json()).toEqual({ data: 'nested function' }) }) it("doesn't serve deeply-nested functions", async () => { const res = await fastifyInstance.inject({ method: 'GET', url: '/deeplyNested/nestedDir/deeplyNested', }) expect(res.statusCode).toEqual(404) expect(res.body).toEqual( 'Function &quot;deeplyNested&quot; was not found.' ) }) }) })
4,049
0
petrpan-code/redwoodjs/redwood/packages/api-server/src
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/withWebServer.test.ts
import fs from 'fs' import path from 'path' import { getPaths } from '@redwoodjs/project-config' import { createFastifyInstance } from '../fastify' import withWebServer from '../plugins/withWebServer' // Suppress terminal logging. console.log = jest.fn() // Set up RWJS_CWD. let original_RWJS_CWD beforeAll(() => { original_RWJS_CWD = process.env.RWJS_CWD process.env.RWJS_CWD = path.join(__dirname, 'fixtures/redwood-app') }) afterAll(() => { process.env.RWJS_CWD = original_RWJS_CWD }) // Set up and teardown the fastify instance with options. let fastifyInstance let returnedFastifyInstance const port = 8910 const message = 'hello from server.config.js' beforeAll(async () => { fastifyInstance = createFastifyInstance() returnedFastifyInstance = await withWebServer(fastifyInstance, { port, // @ts-expect-error just testing that options can be passed through message, }) await fastifyInstance.ready() }) afterAll(async () => { await fastifyInstance.close() }) describe('withWebServer', () => { // Deliberately using `toBe` here to check for referential equality. it('returns the same fastify instance', async () => { expect(returnedFastifyInstance).toBe(fastifyInstance) }) it('can be configured by the user', async () => { const res = await fastifyInstance.inject({ method: 'GET', url: '/test-route', }) expect(res.body).toBe(JSON.stringify({ message })) }) // We can use `printRoutes` with a method for debugging, but not without one. // See https://fastify.dev/docs/latest/Reference/Server#printroutes it('builds a tree of routes for GET', async () => { expect(fastifyInstance.printRoutes({ method: 'GET' })) .toMatchInlineSnapshot(` "└── / β”œβ”€β”€ about (GET) β”œβ”€β”€ contacts/new (GET) β”œβ”€β”€ nested/index (GET) β”œβ”€β”€ test-route (GET) └── * (GET) " `) }) describe('serves prerendered files', () => { it('serves the prerendered about page', async () => { const url = '/about' const res = await fastifyInstance.inject({ method: 'GET', url, }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( fs.readFileSync(path.join(getPaths().web.dist, `${url}.html`), 'utf-8') ) }) it('serves the prerendered new contact page', async () => { const url = '/contacts/new' const res = await fastifyInstance.inject({ method: 'GET', url, }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( fs.readFileSync(path.join(getPaths().web.dist, `${url}.html`), 'utf-8') ) }) // We don't serve files named index.js at the root level. // This logic ensures nested files aren't affected. it('serves the prerendered nested index page', async () => { const url = '/nested/index' const res = await fastifyInstance.inject({ method: 'GET', url, }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( fs.readFileSync(path.join(getPaths().web.dist, `${url}.html`), 'utf-8') ) }) it('serves prerendered files with certain headers', async () => { await fastifyInstance.listen({ port }) const res = await fetch(`http://localhost:${port}/about`) const headers = [...res.headers.keys()] expect(headers).toMatchInlineSnapshot(` [ "accept-ranges", "cache-control", "connection", "content-length", "content-type", "date", "etag", "keep-alive", "last-modified", ] `) }) // I'm not sure if this was intentional, but we support it. // We may want to use the `@fastify/static` plugin's `allowedPath` option. // See https://github.com/fastify/fastify-static?tab=readme-ov-file#allowedpath. it('serves prerendered files at `${routeName}.html`', async () => { const url = '/about.html' const res = await fastifyInstance.inject({ method: 'GET', url, }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( fs.readFileSync(path.join(getPaths().web.dist, url), 'utf-8') ) }) it('handles not found by serving a fallback', async () => { const res = await fastifyInstance.inject({ method: 'GET', url: '/absent.html', }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( fs.readFileSync(path.join(getPaths().web.dist, '200.html'), 'utf-8') ) }) }) describe('serves pretty much anything in web dist', () => { it('serves the built AboutPage.js', async () => { const relativeFilePath = '/assets/AboutPage-7ec0f8df.js' const res = await fastifyInstance.inject({ method: 'GET', url: relativeFilePath, }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe( 'application/javascript; charset=UTF-8' ) expect(res.body).toBe( fs.readFileSync( path.join(getPaths().web.dist, relativeFilePath), 'utf-8' ) ) }) it('serves the built index.css', async () => { const relativeFilePath = '/assets/index-613d397d.css' const res = await fastifyInstance.inject({ method: 'GET', url: relativeFilePath, }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/css; charset=UTF-8') expect(res.body).toBe( fs.readFileSync( path.join(getPaths().web.dist, relativeFilePath), 'utf-8' ) ) }) it('serves build-manifest.json', async () => { const relativeFilePath = '/build-manifest.json' const res = await fastifyInstance.inject({ method: 'GET', url: relativeFilePath, }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe( 'application/json; charset=UTF-8' ) expect(res.body).toBe( fs.readFileSync( path.join(getPaths().web.dist, relativeFilePath), 'utf-8' ) ) }) it('serves favicon.png', async () => { const res = await fastifyInstance.inject({ method: 'GET', url: '/favicon.png', }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('image/png') }) it('serves README.md', async () => { const relativeFilePath = '/README.md' const res = await fastifyInstance.inject({ method: 'GET', url: relativeFilePath, }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/markdown; charset=UTF-8') expect(res.body).toBe( fs.readFileSync( path.join(getPaths().web.dist, relativeFilePath), 'utf-8' ) ) }) it('serves robots.txt', async () => { const relativeFilePath = '/robots.txt' const res = await fastifyInstance.inject({ method: 'GET', url: relativeFilePath, }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/plain; charset=UTF-8') expect(res.body).toBe( fs.readFileSync( path.join(getPaths().web.dist, relativeFilePath), 'utf-8' ) ) }) }) })
4,050
0
petrpan-code/redwoodjs/redwood/packages/api-server/src
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/withWebServerFallback.test.ts
import fs from 'fs' import path from 'path' import { getPaths } from '@redwoodjs/project-config' import { createFastifyInstance } from '../fastify' import withWebServer from '../plugins/withWebServer' // Set up RWJS_CWD. let original_RWJS_CWD beforeAll(() => { original_RWJS_CWD = process.env.RWJS_CWD process.env.RWJS_CWD = path.join(__dirname, 'fixtures/redwood-app-fallback') }) afterAll(() => { process.env.RWJS_CWD = original_RWJS_CWD }) test("handles not found by serving index.html if 200.html doesn't exist", async () => { const fastifyInstance = await withWebServer( createFastifyInstance({ logger: false }), { port: 8910, } ) const url = '/index.html' const res = await fastifyInstance.inject({ method: 'GET', url, }) expect(res.statusCode).toBe(200) expect(res.headers['content-type']).toBe('text/html; charset=UTF-8') expect(res.body).toBe( fs.readFileSync(path.join(getPaths().web.dist, url), 'utf-8') ) await fastifyInstance.close() })
4,051
0
petrpan-code/redwoodjs/redwood/packages/api-server/src
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/withWebServerLoadFastifyConfig.test.ts
import { vol } from 'memfs' import { createFastifyInstance } from '../fastify' import withWebServer from '../plugins/withWebServer' // Suppress terminal logging. console.log = jest.fn() // Set up RWJS_CWD. let original_RWJS_CWD const FIXTURE_PATH = '/redwood-app' beforeAll(() => { original_RWJS_CWD = process.env.RWJS_CWD process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { process.env.RWJS_CWD = original_RWJS_CWD }) // Mock server.config.js. jest.mock('fs', () => require('memfs').fs) jest.mock( '/redwood-app/api/server.config.js', () => { return { config: {}, configureFastify: async (fastify, options) => { if (options.side === 'web') { fastify.get('/about.html', async (_request, _reply) => { return { virtualAboutHtml: true } }) } return fastify }, } }, { virtual: true } ) jest.mock( '\\redwood-app\\api\\server.config.js', () => { return { config: {}, configureFastify: async (fastify, options) => { if (options.side === 'web') { fastify.get('/about.html', async (_request, _reply) => { return { virtualAboutHtml: true } }) } return fastify }, } }, { virtual: true } ) test("the user can overwrite static files that weren't set specifically ", async () => { vol.fromNestedJSON( { 'redwood.toml': '', api: { 'server.config.js': '', }, web: { dist: { 'about.html': '<h1>About</h1>', }, }, }, FIXTURE_PATH ) const fastifyInstance = await withWebServer(createFastifyInstance(), { port: 8910, }) const res = await fastifyInstance.inject({ method: 'GET', url: '/about.html', }) expect(res.statusCode).toBe(200) expect(res.body).toBe(JSON.stringify({ virtualAboutHtml: true })) await fastifyInstance.close() })
4,052
0
petrpan-code/redwoodjs/redwood/packages/api-server/src
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/withWebServerLoadFastifyConfigError.test.ts
import { vol } from 'memfs' import { createFastifyInstance } from '../fastify' import withWebServer from '../plugins/withWebServer' // Suppress terminal logging. console.log = jest.fn() // Set up RWJS_CWD. let original_RWJS_CWD const FIXTURE_PATH = '/redwood-app' beforeAll(() => { original_RWJS_CWD = process.env.RWJS_CWD process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { process.env.RWJS_CWD = original_RWJS_CWD }) // Mock server.config.js. jest.mock('fs', () => require('memfs').fs) const aboutHTML = '<h1>About</h1>' jest.mock( '/redwood-app/api/server.config.js', () => { return { config: {}, configureFastify: async (fastify, options) => { if (options.side === 'web') { fastify.get('/about', async (_request, _reply) => { return { virtualAboutHtml: true } }) } return fastify }, } }, { virtual: true } ) jest.mock( '\\redwood-app\\api\\server.config.js', () => { return { config: {}, configureFastify: async (fastify, options) => { if (options.side === 'web') { fastify.get('/about', async (_request, _reply) => { return { virtualAboutHtml: true } }) } return fastify }, } }, { virtual: true } ) test("the user can't overwrite prerendered files", async () => { vol.fromNestedJSON( { 'redwood.toml': '', api: { 'server.config.js': '', }, web: { dist: { 'about.html': aboutHTML, }, }, }, FIXTURE_PATH ) try { await withWebServer(createFastifyInstance(), { port: 8910, }) } catch (e) { expect(e.code).toBe('FST_ERR_DUPLICATED_ROUTE') } })
4,080
0
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/requestHandlers/awsLambdaFastify.test.ts
import type { FastifyRequest, FastifyReply } from 'fastify' import { requestHandler } from '../../requestHandlers/awsLambdaFastify' describe('Tests AWS Lambda to Fastify request transformation and handling', () => { beforeEach(() => { jest.clearAllMocks() }) const request = { method: 'GET', body: '', headers: '', query: '/', params: {}, url: '/', urlData: () => ({ path: '/' }), log: console as unknown, } as unknown as FastifyRequest const mockedReply = { status: (code) => { return { code, send: jest.fn() } }, headers: (h) => jest.fn(h), header: (h) => jest.fn(h), send: (body) => jest.fn(body), log: console as unknown, } as unknown as FastifyReply test('requestHandler replies with simple body', async () => { jest.spyOn(mockedReply, 'send') jest.spyOn(mockedReply, 'status') const handler = async (req, mockedReply) => { mockedReply = { body: { foo: 'bar' } } return mockedReply } await requestHandler(request, mockedReply, handler) expect(mockedReply.send).toHaveBeenCalledWith({ foo: 'bar' }) expect(mockedReply.status).toHaveBeenCalledWith(200) }) test('requestHandler replies with a base64Encoded body', async () => { jest.spyOn(mockedReply, 'send') jest.spyOn(mockedReply, 'status') const handler = async (req, mockedReply) => { mockedReply = { body: 'this_is_a_test_of_base64Encoding', isBase64Encoded: true, } return mockedReply } await requestHandler(request, mockedReply, handler) expect(mockedReply.send).toHaveBeenCalledWith( Buffer.from('this_is_a_test_of_base64Encoding', 'base64') ) expect(mockedReply.status).toHaveBeenCalledWith(200) }) describe('error handling', () => { let consoleError beforeEach(() => { consoleError = console.error console.error = () => {} }) afterEach(() => { console.error = consoleError }) test('requestHandler returns an error status if handler throws an error', async () => { jest.spyOn(mockedReply, 'status') const handler = async () => { throw new Error('error') } await requestHandler(request, mockedReply, handler) expect(mockedReply.status).toHaveBeenCalledWith(500) }) }) test('requestHandler replies with headers', async () => { const headersRequest = { method: 'GET', body: '', headers: {}, query: '/', params: {}, url: '/', urlData: () => ({ path: '/' }), log: console as unknown, } as unknown as FastifyRequest jest.spyOn(mockedReply, 'headers') jest.spyOn(mockedReply, 'header') const handler = async (req, mockedReply) => { mockedReply = { body: { foo: 'bar' }, headers: { 'content-type': 'application/json', authorization: 'Bearer token 123', }, } return mockedReply } await requestHandler(headersRequest, mockedReply, handler) expect(mockedReply.headers).not.toHaveBeenCalled() expect(mockedReply.header).toHaveBeenCalledWith( 'content-type', 'application/json' ) expect(mockedReply.header).toHaveBeenCalledWith( 'authorization', 'Bearer token 123' ) }) test('requestHandler replies with multi-value headers', async () => { const headersRequest = { method: 'GET', body: '', headers: {}, query: '/', params: {}, url: '/', urlData: () => ({ path: '/' }), log: console as unknown, } as unknown as FastifyRequest jest.spyOn(mockedReply, 'headers') jest.spyOn(mockedReply, 'header') const handler = async (_req, mockedReply) => { mockedReply = { body: {}, headers: {}, multiValueHeaders: { 'content-type': ['application/json', 'text/html'], }, } return mockedReply } await requestHandler(headersRequest, mockedReply, handler) expect(mockedReply.headers).not.toHaveBeenCalled() expect(mockedReply.header).toHaveBeenCalledWith( 'content-type', 'application/json; text/html' ) }) })
4,081
0
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__
petrpan-code/redwoodjs/redwood/packages/api-server/src/__tests__/requestHandlers/utils.test.ts
import { parseBody, mergeMultiValueHeaders } from '../../requestHandlers/utils' describe('Tests AWS Lambda to Fastify utility functions', () => { describe('Tests parseBody', () => { test('with a string', () => { const parsed = parseBody('foo') expect(parsed).toEqual({ body: 'foo', isBase64Encoded: false }) }) test('with a buffer', () => { const buf = Buffer.from('foo', 'base64') const parsed = parseBody(buf) expect(parsed).toEqual({ body: 'foo=', isBase64Encoded: true }) }) }) describe('Tests mergeMultiValueHeaders', () => { test('with same header', () => { const headers = { 'content-type': 'application/json' } const multiValueHeaders = { 'content-type': ['application/json', 'text/html'], } const merged = mergeMultiValueHeaders(headers, multiValueHeaders) expect(merged).toEqual({ 'content-type': ['application/json; text/html'], }) }) test('with multi-value header that is title-cased', () => { const headers = { 'content-type': 'application/json' } const multiValueHeaders = { 'Content-Type': ['application/json', 'text/html'], } const merged = mergeMultiValueHeaders(headers, multiValueHeaders) expect(merged).toEqual({ 'content-type': ['application/json; text/html'], }) }) test('when no headers, but has multi-value headers', () => { const headers = {} const multiValueHeaders = { 'content-type': ['application/json', 'text/html'], } const merged = mergeMultiValueHeaders(headers, multiValueHeaders) expect(merged).toEqual({ 'content-type': ['application/json; text/html'], }) }) test('set-cookie', () => { const headers = {} const multiValueHeaders = { 'Set-Cookie': ['rob=TS4Life', 'danny=kittens'], } const merged = mergeMultiValueHeaders(headers, multiValueHeaders) expect(merged).toEqual({ 'set-cookie': ['rob=TS4Life', 'danny=kittens'], }) }) test('set-cookie in both headers and multiValueHeaders', () => { const headers = { 'set-cookie': 'peter=snaplet' } const multiValueHeaders = { 'set-cookie': ['peter=snaplet', 'tom=hammer'], } const merged = mergeMultiValueHeaders(headers, multiValueHeaders) expect(merged).toEqual({ 'set-cookie': ['peter=snaplet', 'tom=hammer'], }) }) }) })
4,110
0
petrpan-code/redwoodjs/redwood/packages/api/src
petrpan-code/redwoodjs/redwood/packages/api/src/__tests__/normalizeRequest.test.ts
import { Headers } from '@whatwg-node/fetch' import type { APIGatewayProxyEvent } from 'aws-lambda' import { normalizeRequest } from '../transforms' export const createMockedEvent = ( httpMethod = 'POST', body: any = undefined, isBase64Encoded = false ): APIGatewayProxyEvent => { return { body, headers: {}, multiValueHeaders: {}, httpMethod, isBase64Encoded, path: '/MOCK_PATH', pathParameters: null, queryStringParameters: null, multiValueQueryStringParameters: null, stageVariables: null, requestContext: { accountId: 'MOCKED_ACCOUNT', apiId: 'MOCKED_API_ID', authorizer: { name: 'MOCKED_AUTHORIZER' }, protocol: 'HTTP', identity: { accessKey: null, accountId: null, apiKey: null, apiKeyId: null, caller: null, clientCert: null, cognitoAuthenticationProvider: null, cognitoAuthenticationType: null, cognitoIdentityId: null, cognitoIdentityPoolId: null, principalOrgId: null, sourceIp: '123.123.123.123', user: null, userAgent: null, userArn: null, }, httpMethod: 'POST', path: '/MOCK_PATH', stage: 'MOCK_STAGE', requestId: 'MOCKED_REQUEST_ID', requestTimeEpoch: 1, resourceId: 'MOCKED_RESOURCE_ID', resourcePath: 'MOCKED_RESOURCE_PATH', }, resource: 'MOCKED_RESOURCE', } } test('Normalizes an aws event with base64', () => { const corsEventB64 = createMockedEvent( 'POST', Buffer.from(JSON.stringify({ bazinga: 'hello_world' }), 'utf8').toString( 'base64' ), true ) expect(normalizeRequest(corsEventB64)).toEqual({ headers: new Headers(corsEventB64.headers), method: 'POST', query: null, body: { bazinga: 'hello_world', }, }) }) test('Handles CORS requests with and without b64 encoded', () => { const corsEventB64 = createMockedEvent('OPTIONS', undefined, true) expect(normalizeRequest(corsEventB64)).toEqual({ headers: new Headers(corsEventB64.headers), // headers returned as symbol method: 'OPTIONS', query: null, body: undefined, }) const corsEventWithoutB64 = createMockedEvent('OPTIONS', undefined, false) expect(normalizeRequest(corsEventWithoutB64)).toEqual({ headers: new Headers(corsEventB64.headers), // headers returned as symbol method: 'OPTIONS', query: null, body: undefined, }) })
4,111
0
petrpan-code/redwoodjs/redwood/packages/api/src
petrpan-code/redwoodjs/redwood/packages/api/src/__tests__/transforms.test.ts
import { removeNulls } from '../transforms' describe('removeNulls utility', () => { it('Changes nulls to undefined', () => { const input = { a: null, b: 'b', c: { d: null, // nested null e: 3, f: { g: null, // deeply nested null h: [null, null], // array of nulls is also transformed i: [1, 2, null, 4], }, }, myDate: new Date('2020-01-01'), } const result = removeNulls(input) expect(result).toEqual({ a: undefined, b: 'b', c: { d: undefined, e: 3, f: { g: undefined, h: [undefined, undefined], i: [1, 2, undefined, 4], }, }, myDate: new Date('2020-01-01'), }) }) })
4,114
0
petrpan-code/redwoodjs/redwood/packages/api/src/auth
petrpan-code/redwoodjs/redwood/packages/api/src/auth/__tests__/getAuthenticationContext.test.ts
import type { APIGatewayProxyEvent, Context } from 'aws-lambda' import { getAuthenticationContext } from '../index' export const createMockedEvent = ({ authProvider, }: { authProvider: string }): APIGatewayProxyEvent => { return { body: null, headers: { 'auth-provider': authProvider, authorization: 'Bearer auth-test-token', }, multiValueHeaders: {}, httpMethod: 'POST', isBase64Encoded: false, path: '/MOCK_PATH', pathParameters: null, queryStringParameters: null, multiValueQueryStringParameters: null, stageVariables: null, requestContext: { accountId: 'MOCKED_ACCOUNT', apiId: 'MOCKED_API_ID', authorizer: { name: 'MOCKED_AUTHORIZER' }, protocol: 'HTTP', identity: { accessKey: null, accountId: null, apiKey: null, apiKeyId: null, caller: null, clientCert: null, cognitoAuthenticationProvider: null, cognitoAuthenticationType: null, cognitoIdentityId: null, cognitoIdentityPoolId: null, principalOrgId: null, sourceIp: '123.123.123.123', user: null, userAgent: null, userArn: null, }, httpMethod: 'POST', path: '/MOCK_PATH', stage: 'MOCK_STAGE', requestId: 'MOCKED_REQUEST_ID', requestTimeEpoch: 1, resourceId: 'MOCKED_RESOURCE_ID', resourcePath: 'MOCKED_RESOURCE_PATH', }, resource: 'MOCKED_RESOURCE', } } describe('getAuthenticationContext', () => { it('Can take a single auth decoder for the given provider', async () => { const authDecoderOne = async (_token: string, type: string) => { if (type !== 'one') { return null } return { iss: 'one', sub: 'user-id', } } const result = await getAuthenticationContext({ authDecoder: authDecoderOne, event: createMockedEvent({ authProvider: 'one' }), context: {} as Context, }) if (!result) { fail('Result is undefined') } const [decoded, { type, schema, token }] = result expect(decoded).toMatchObject({ iss: 'one', sub: 'user-id', }) expect(type).toEqual('one') expect(schema).toEqual('Bearer') expect(token).toEqual('auth-test-token') }) it('Can take a single auth decoder for some other provider', async () => { const authDecoderOne = async (_token: string, type: string) => { if (type !== 'one') { return null } return { iss: 'one', sub: 'user-id', } } const result = await getAuthenticationContext({ authDecoder: authDecoderOne, event: createMockedEvent({ authProvider: 'some-other' }), context: {} as Context, }) if (!result) { fail('Result is undefined') } const [decoded, { type, schema, token }] = result expect(decoded).toBeNull() expect(type).toEqual('some-other') expect(schema).toEqual('Bearer') expect(token).toEqual('auth-test-token') }) it('Can take an empty array of auth decoders', async () => { const result = await getAuthenticationContext({ authDecoder: [], event: createMockedEvent({ authProvider: 'two' }), context: {} as Context, }) if (!result) { fail('Result is undefined') } const [decoded, { type, schema, token }] = result expect(decoded).toBeNull() expect(type).toEqual('two') expect(schema).toEqual('Bearer') expect(token).toEqual('auth-test-token') }) it('Can take an array of auth decoders', async () => { const authDecoderOne = async (_token: string, type: string) => { if (type !== 'one') { return null } return { iss: 'one', sub: 'user-id', } } const authDecoderTwo = async (_token: string, type: string) => { if (type !== 'two') { return null } return { iss: 'two', sub: 'user-id', } } const result = await getAuthenticationContext({ authDecoder: [authDecoderOne, authDecoderTwo], event: createMockedEvent({ authProvider: 'two' }), context: {} as Context, }) if (!result) { fail('Result is undefined') } const [decoded, { type, schema, token }] = result expect(decoded).toMatchObject({ iss: 'two', sub: 'user-id', }) expect(type).toEqual('two') expect(schema).toEqual('Bearer') expect(token).toEqual('auth-test-token') }) it('Works even without any auth decoders', async () => { const result = await getAuthenticationContext({ event: createMockedEvent({ authProvider: 'two' }), context: {} as Context, }) if (!result) { fail('Result is undefined') } const [decoded, { type, schema, token }] = result expect(decoded).toEqual(null) expect(type).toEqual('two') expect(schema).toEqual('Bearer') expect(token).toEqual('auth-test-token') }) })
4,115
0
petrpan-code/redwoodjs/redwood/packages/api/src/auth
petrpan-code/redwoodjs/redwood/packages/api/src/auth/__tests__/parseJWT.test.ts
import { parseJWT } from '../parseJWT' const JWT_CLAIMS: Record<string, unknown> = { iss: 'https://app.us.auth0.com/', sub: 'email|1234', aud: ['https://example.com', 'https://app.us.auth0.com/userinfo'], iat: 1596481520, exp: 1596567920, azp: '1l0w6JXXXXL880T', scope: 'openid profile email', } const JWT_WITH_AUTHORIZATION = { app_metadata: { authorization: { roles: ['editor', 'publisher'] } }, user_metadata: {}, } const JWT = { app_metadata: { roles: ['author'] }, user_metadata: {}, ...JWT_CLAIMS, } const NAMESPACE = 'https://example.com' const NAMESPACED_JWT_WITH_AUTHORIZATION = { 'https://example.com/app_metadata': { authorization: { roles: ['admin'] } }, 'https://example.com/user_metadata': {}, ...JWT_CLAIMS, } const NAMESPACED_JWT = { 'https://example.com/app_metadata': { roles: ['member'] }, 'https://example.com/user_metadata': {}, ...JWT_CLAIMS, } const JWT_WITH_ROLES_CLAIM = { roles: ['customer'], ...JWT_CLAIMS, } describe('parseJWT', () => { describe('handle empty token cases', () => { test('it handles null token and returns empty appMetadata and roles', () => { const token = { decoded: null, namespace: null } expect(parseJWT(token)).toEqual({ appMetadata: {}, roles: [] }) }) test('it handles an undefined token and returns empty appMetadata and roles', () => { const token = { decoded: undefined, namespace: undefined } expect(parseJWT(token)).toEqual({ appMetadata: {}, roles: [] }) }) test('it handles an undefined decoded token and returns empty appMetadata and roles', () => { const token = { decoded: undefined, namespace: null } expect(parseJWT(token)).toEqual({ appMetadata: {}, roles: [] }) }) test('it handles an undefined namespace in token and returns empty appMetadata and roles', () => { const token = { decoded: null, namespace: undefined } expect(parseJWT(token)).toEqual({ appMetadata: {}, roles: [] }) }) }) describe('when the token has an app_metadata custom claim', () => { test('it parses and returns appMetadata and expected roles', () => { const token = { decoded: JWT, } expect(parseJWT(token)).toEqual({ appMetadata: { roles: ['author'] }, roles: ['author'], }) }) test('it parses and returns appMetadata with authorization and expected roles', () => { const token = { decoded: JWT_WITH_AUTHORIZATION, } expect(parseJWT(token)).toEqual({ appMetadata: { authorization: { roles: ['editor', 'publisher'] } }, roles: ['editor', 'publisher'], }) }) }) describe('when the token has a namespaced app_metadata custom claim', () => { test('it parses and returns appMetadata and expected roles', () => { const token = { decoded: NAMESPACED_JWT, namespace: NAMESPACE, } expect(parseJWT(token)).toEqual({ appMetadata: { roles: ['member'] }, roles: ['member'], }) }) test('it parses and returns appMetadata with authorization and expected roles', () => { const token = { decoded: NAMESPACED_JWT_WITH_AUTHORIZATION, namespace: NAMESPACE, } expect(parseJWT(token)).toEqual({ appMetadata: { authorization: { roles: ['admin'] } }, roles: ['admin'], }) }) }) describe('when the token has a roles custom claim', () => { test('it parses and returns expected roles', () => { const token = { decoded: JWT_WITH_ROLES_CLAIM, } expect(parseJWT(token)).toEqual({ appMetadata: {}, roles: ['customer'], }) }) }) })
4,126
0
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers/__tests__/base64Sha1Verifier.test.ts
import { createVerifier, WebhookVerificationError } from '../index' const stringPayload = 'No more secrets, Marty.' const payload = { data: { move: 'Sneakers', quote: stringPayload } } const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' const { sign, verify } = createVerifier('base64Sha1Verifier') describe('base64 sha1 verifier', () => { describe('signs a payload with the sha1 algorithm', () => { test('it verifies when signed and verified with same secret', () => { const signature = sign({ payload, secret }) expect(verify({ payload, secret, signature })).toBeTruthy() }) test('it denies verification if signature does not represent the secret signed payload', () => { const signature = 'sha7=819468bd4f892c51d2aee3b0842afc2e397d3798d1be0ca9b89273c3f97b1b7a' expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) test('it denies verification if the secret used to sign does not match the signature', () => { const signature = sign({ payload, secret: 'I_LEAVE_MESSAGE_HERE_ON_SERVICE_BUT_YOU_DO_NOT_CALL', }) expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) describe('signs a string payload with the sha1 algorithm', () => { test('it verifies when signed and verified with same secret', () => { const signature = sign({ payload: stringPayload, secret }) expect(verify({ payload: stringPayload, secret, signature })).toBeTruthy() }) test('it denies verification if signature does not represent the secret signed payload', () => { const signature = 'sha7=819468bd4f892c51d2aee3b0842afc2e397d3798d1be0ca9b89273c3f97b1b7a' expect(() => { verify({ payload: stringPayload, secret, signature }) }).toThrow(WebhookVerificationError) }) test('it denies verification if the secret used to sign does not match the signature', () => { const signature = sign({ payload: stringPayload, secret: 'I_LEAVE_MESSAGE_HERE_ON_SERVICE_BUT_YOU_DO_NOT_CALL', }) expect(() => { verify({ payload: stringPayload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) })
4,127
0
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers/__tests__/base64Sha256Verifier.test.ts
import { createVerifier, WebhookVerificationError } from '../index' const stringPayload = 'No more secrets, Marty.' const payload = { data: { move: 'Sneakers', quote: stringPayload } } const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' const { sign, verify } = createVerifier('base64Sha256Verifier') describe('base64 sha256 verifier', () => { describe('signs a payload with the sha256 algorithm', () => { test('it verifies when signed and verified with same secret', () => { const signature = sign({ payload, secret }) expect(verify({ payload, secret, signature })).toBeTruthy() }) test('it denies verification if signature does not represent the secret signed payload', () => { const signature = 'sha265=819468bd4f892c51d2aee3b0842afc2e397d3798d1be0ca9b89273c3f97b1b7a' expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) test('it denies verification if the secret used to sign does not match the signature', () => { const signature = sign({ payload, secret: 'I_LEAVE_MESSAGE_HERE_ON_SERVICE_BUT_YOU_DO_NOT_CALL', }) expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) describe('signs a string payload with the sha256 algorithm', () => { test('it verifies when signed and verified with same secret', () => { const signature = sign({ payload: stringPayload, secret }) expect(verify({ payload: stringPayload, secret, signature })).toBeTruthy() }) test('it denies verification if signature does not represent the secret signed payload', () => { const signature = 'sha265=819468bd4f892c51d2aee3b0842afc2e397d3798d1be0ca9b89273c3f97b1b7a' expect(() => { verify({ payload: stringPayload, secret, signature }) }).toThrow(WebhookVerificationError) }) test('it denies verification if the secret used to sign does not match the signature', () => { const signature = sign({ payload: stringPayload, secret: 'I_LEAVE_MESSAGE_HERE_ON_SERVICE_BUT_YOU_DO_NOT_CALL', }) expect(() => { verify({ payload: stringPayload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) })
4,128
0
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers/__tests__/jwtVerifier.test.ts
import { createVerifier, WebhookSignError, WebhookVerificationError, } from '../index' const payload = { data: 'No more secrets, Marty.' } const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' describe('jwtVerifier verifier', () => { describe('signs a payload', () => { test('it has a signature', () => { const { sign } = createVerifier('jwtVerifier') const signature = sign({ payload, secret }) expect(signature).toMatch( /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/ ) }) }) describe('fails to sign a payload', () => { test('that it has signed with issuer claim but a string payload', () => { const { sign } = createVerifier('jwtVerifier', { issuer: 'redwoodjs.com', }) expect(() => { sign({ payload: '273-9164. Area code 415.', secret }) }).toThrow(WebhookSignError) }) }) describe('it verifies JWT', () => { test('that it has signed', () => { const { sign, verify } = createVerifier('jwtVerifier') const signature = sign({ payload, secret }) expect(verify({ payload, secret, signature })).toBeTruthy() }) test('that it has signed with issuer claim', () => { const { sign, verify } = createVerifier('jwtVerifier', { issuer: 'redwoodjs.com', }) const signature = sign({ payload, secret }) expect(verify({ payload, secret, signature })).toBeTruthy() }) }) describe('it denies a JWT', () => { test('that it has signed with a different secret', () => { const { sign, verify } = createVerifier('jwtVerifier') const signature = sign({ payload, secret }) expect(() => { verify({ payload, secret: 'not so secret', signature }) }).toThrow(WebhookVerificationError) }) test('that it has signed with a different issuer', () => { const { sign } = createVerifier('jwtVerifier', { issuer: 'redwoodjs.com', }) const signature = sign({ payload, secret }) const { verify } = createVerifier('jwtVerifier', { issuer: 'example.com', }) expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) })
4,129
0
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers/__tests__/secretKeyVerifier.test.ts
import { createVerifier, WebhookVerificationError } from '../index' const payload = 'No more secrets, Marty.' const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' const { sign, verify } = createVerifier('secretKeyVerifier') beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(jest.fn()) }) afterEach(() => { jest.spyOn(console, 'warn').mockRestore() }) describe('secretKey verifier', () => { describe('faux signs a payload', () => { test('a signature is the secret itself', () => { const signature = sign({ payload, secret }) expect(signature).toEqual(secret) }) test('it verifies that the secret and signature are identical', () => { jest.spyOn(console, 'warn').mockImplementation(jest.fn()) const signature = sign({ payload, secret }) expect(verify({ payload, secret, signature })).toBeTruthy() jest.spyOn(console, 'warn').mockRestore() }) test('it denies verification if the secret and signature are not the same', () => { const signature = 'I_LEAVE_MESSAGE_HERE_ON_SERVICE_BUT_YOU_DO_NOT_CALL' expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) })
4,130
0
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers/__tests__/sha1Verifier.test.ts
import { createVerifier, WebhookVerificationError } from '../index' const stringPayload = 'No more secrets, Marty.' const payload = { data: { move: 'Sneakers', quote: stringPayload } } const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' const { sign, verify } = createVerifier('sha1Verifier') describe('sha1 verifier', () => { describe('signs a payload with the sha1 algorithm', () => { test('the signature matches the algorithm format', () => { const signature = sign({ payload, secret }) expect(signature).toMatch(/sha1=([\da-f]+)/) }) test('it verifies when signed and verified with same secret', () => { const signature = sign({ payload, secret }) expect(verify({ payload, secret, signature })).toBeTruthy() }) test('it denies verification if signature does not represent the secret signed payload', () => { const signature = 'sha1=220ddac4a81ca8a14716bd74c2b3134cae17d2fc' expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) test('it denies verification if the secret used to sign does not match the signature', () => { const signature = sign({ payload, secret: 'I_LEAVE_MESSAGE_HERE_ON_SERVICE_BUT_YOU_DO_NOT_CALL', }) expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) describe('signs a string payload with the sha1 algorithm', () => { test('the signature matches the algorithm format', () => { const signature = sign({ payload: stringPayload, secret }) expect(signature).toMatch(/sha1=([\da-f]+)/) }) test('it verifies when signed and verified with same secret', () => { const signature = sign({ payload: stringPayload, secret }) expect(verify({ payload: stringPayload, secret, signature })).toBeTruthy() }) test('it denies verification if signature does not represent the secret signed payload', () => { const signature = 'sha1=a20ddac4a81ba8a147162d74c2b3134cae17d2fc' expect(() => { verify({ payload: stringPayload, secret, signature }) }).toThrow(WebhookVerificationError) }) test('it denies verification if the secret used to sign does not match the signature', () => { const signature = sign({ payload: stringPayload, secret: 'I_LEAVE_MESSAGE_HERE_ON_SERVICE_BUT_YOU_DO_NOT_CALL', }) expect(() => { verify({ payload: stringPayload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) })
4,131
0
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers/__tests__/sha256Verifier.test.ts
import { createVerifier, WebhookVerificationError } from '../index' const stringPayload = 'No more secrets, Marty.' const payload = { data: { move: 'Sneakers', quote: stringPayload } } const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' const { sign, verify } = createVerifier('sha256Verifier') describe('sha256 verifier', () => { describe('signs a payload with the sha256 algorithm', () => { test('the signature matches the algorithm format', () => { const signature = sign({ payload, secret }) expect(signature).toMatch(/sha256=([\da-f]+)/) }) test('it verifies when signed and verified with same secret', () => { const signature = sign({ payload, secret }) expect(verify({ payload, secret, signature })).toBeTruthy() }) test('it denies verification if signature does not represent the secret signed payload', () => { const signature = 'sha265=819468bd4f892c51d2aee3b0842afc2e397d3798d1be0ca9b89273c3f97b1b7a' expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) test('it denies verification if the secret used to sign does not match the signature', () => { const signature = sign({ payload, secret: 'I_LEAVE_MESSAGE_HERE_ON_SERVICE_BUT_YOU_DO_NOT_CALL', }) expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) describe('signs a string payload with the sha256 algorithm', () => { test('the signature matches the algorithm format', () => { const signature = sign({ payload: stringPayload, secret }) expect(signature).toMatch(/sha256=([\da-f]+)/) }) test('it verifies when signed and verified with same secret', () => { const signature = sign({ payload: stringPayload, secret }) expect(verify({ payload: stringPayload, secret, signature })).toBeTruthy() }) test('it denies verification if signature does not represent the secret signed payload', () => { const signature = 'sha265=819468bd4f892c51d2aee3b0842afc2e397d3798d1be0ca9b89273c3f97b1b7a' expect(() => { verify({ payload: stringPayload, secret, signature }) }).toThrow(WebhookVerificationError) }) test('it denies verification if the secret used to sign does not match the signature', () => { const signature = sign({ payload: stringPayload, secret: 'I_LEAVE_MESSAGE_HERE_ON_SERVICE_BUT_YOU_DO_NOT_CALL', }) expect(() => { verify({ payload: stringPayload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) })
4,132
0
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers/__tests__/skipVerifier.test.ts
import { createVerifier } from '../index' const payload = 'No more secrets, Marty.' const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' const { sign, verify } = createVerifier('skipVerifier') beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(jest.fn()) }) afterEach(() => { jest.spyOn(console, 'warn').mockRestore() }) describe('skips verification verifier', () => { describe('faux signs a payload', () => { test('it has an empty signature', () => { const signature = sign({ payload, secret }) expect(signature).toEqual('') }) test('it always verifies', () => { const signature = sign({ payload, secret }) expect(verify({ payload, secret, signature })).toBeTruthy() }) }) })
4,133
0
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers
petrpan-code/redwoodjs/redwood/packages/api/src/auth/verifiers/__tests__/timestampSchemeVerifier.test.ts
// import type { APIGatewayProxyEvent } from 'aws-lambda' import { createVerifier, WebhookVerificationError } from '../index' const payload = 'No more secrets, Marty.' const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' describe('timestampScheme verifier', () => { describe('signs a payload with default timestamp', () => { test('it has a time and scheme', () => { const { sign } = createVerifier('timestampSchemeVerifier') const signature = sign({ payload, secret }) expect(signature).toMatch(/t=(\d+),v1=([\da-f]+)/) }) test('it can verify a signature it generates', () => { const { sign, verify } = createVerifier('timestampSchemeVerifier') const signature = sign({ payload, secret }) expect(verify({ payload, secret, signature })).toBeTruthy() }) test('it denies a signature when signed with a different secret', () => { const { sign, verify } = createVerifier('timestampSchemeVerifier') const signature = sign({ payload, secret: 'WERNER_BRANDES' }) expect(() => { verify({ payload, secret, signature }) }).toThrow(WebhookVerificationError) }) }) describe('signs a payload with varying timestamps and tolerances', () => { test('it denies a signature when verifying with a short tolerance', () => { const { sign } = createVerifier('timestampSchemeVerifier', { currentTimestampOverride: Date.now() - 600_000, // 10 minutes in msec }) const { verify } = createVerifier('timestampSchemeVerifier', { tolerance: 120_000, // 2 minutes in msec }) const signature = sign({ payload, secret, }) expect(() => { verify({ payload, secret, signature, }) }).toThrow(WebhookVerificationError) }) test('it denies a signature when verifying when outside the default tolerance', () => { const { sign } = createVerifier('timestampSchemeVerifier', { currentTimestampOverride: Date.now() - 600_000, // 10 minutes in msec }) // uses default 5 minute tolerance const { verify } = createVerifier('timestampSchemeVerifier') const signature = sign({ payload, secret, }) expect(() => { verify({ payload, secret, signature, }) }).toThrow(WebhookVerificationError) }) }) })
4,139
0
petrpan-code/redwoodjs/redwood/packages/api/src/cache
petrpan-code/redwoodjs/redwood/packages/api/src/cache/__tests__/cache.test.ts
import InMemoryClient from '../clients/InMemoryClient' import { createCache } from '../index' describe('cache', () => { it('adds a missing key to the cache', async () => { const client = new InMemoryClient() const { cache } = createCache(client) const result = await cache('test', () => { return { foo: 'bar' } }) expect(result).toEqual({ foo: 'bar' }) expect(client.storage.test.value).toEqual(JSON.stringify({ foo: 'bar' })) }) it('finds an existing key in the cache', async () => { const client = new InMemoryClient({ test: { expires: 1977175194415, value: '{"foo":"bar"}' }, }) const { cache } = createCache(client) const result = await cache('test', () => { return { bar: 'baz' } }) // returns existing cached value, not the one that was just set expect(result).toEqual({ foo: 'bar' }) }) })
4,140
0
petrpan-code/redwoodjs/redwood/packages/api/src/cache
petrpan-code/redwoodjs/redwood/packages/api/src/cache/__tests__/cacheFindMany.test.ts
import { PrismaClient } from '@prisma/client' import InMemoryClient from '../clients/InMemoryClient' import { createCache } from '../index' const mockFindFirst = jest.fn() const mockFindMany = jest.fn() jest.mock('@prisma/client', () => ({ PrismaClient: jest.fn(() => ({ user: { findFirst: mockFindFirst, findMany: mockFindMany, }, })), })) describe('cacheFindMany', () => { afterEach(() => { jest.clearAllMocks() }) it('adds the collection to the cache based on latest updated user', async () => { const now = new Date() const user = { id: 1, email: '[email protected]', updatedAt: now, } mockFindFirst.mockImplementation(() => user) mockFindMany.mockImplementation(() => [user]) const client = new InMemoryClient() const { cacheFindMany } = createCache(client) const spy = jest.spyOn(client, 'set') await cacheFindMany('test', PrismaClient().user) expect(spy).toHaveBeenCalled() expect(client.storage[`test-1-${now.getTime()}`].value).toEqual( JSON.stringify([user]) ) }) it('adds a new collection if a record has been updated', async () => { const now = new Date() const user = { id: 1, email: '[email protected]', updatedAt: now, } const client = new InMemoryClient({ [`test-1-${now.getTime()}`]: { expires: 1977175194415, value: JSON.stringify([user]), }, }) // set mock to return user that's been updated in the future, rather than // the timestamp that's been cached already const future = new Date() future.setSeconds(future.getSeconds() + 1000) user.updatedAt = future mockFindFirst.mockImplementation(() => user) mockFindMany.mockImplementation(() => [user]) const { cacheFindMany } = createCache(client) const spy = jest.spyOn(client, 'set') await cacheFindMany('test', PrismaClient().user) expect(spy).toHaveBeenCalled() // the `now` cache still exists expect( JSON.parse(client.storage[`test-1-${now.getTime()}`].value)[0].id ).toEqual(1) // the `future` cache should have been created expect(client.storage[`test-1-${future.getTime()}`].value).toEqual( JSON.stringify([user]) ) }) it('skips caching and just runs the findMany() if there are no records', async () => { const client = new InMemoryClient() mockFindFirst.mockImplementation(() => null) mockFindMany.mockImplementation(() => []) const { cacheFindMany } = createCache(client) const getSpy = jest.spyOn(client, 'get') const setSpy = jest.spyOn(client, 'set') const result = await cacheFindMany('test', PrismaClient().user) expect(result).toEqual([]) expect(getSpy).not.toHaveBeenCalled() expect(setSpy).not.toHaveBeenCalled() }) })
4,142
0
petrpan-code/redwoodjs/redwood/packages/api/src/cache
petrpan-code/redwoodjs/redwood/packages/api/src/cache/__tests__/disconnect.test.ts
import InMemoryClient from '../clients/InMemoryClient' import { CacheTimeoutError } from '../errors' import { createCache } from '../index' describe('client.disconnect', () => { beforeEach(() => { jest.clearAllMocks() }) it('attempts to disconnect on timeout error', async () => { const client = new InMemoryClient() const { cache } = createCache(client) const getSpy = jest.spyOn(client, 'get') getSpy.mockImplementation(() => { throw new CacheTimeoutError() }) const disconnectSpy = jest.spyOn(client, 'disconnect') await cache('test', () => { return { bar: 'baz' } }) // returns existing cached value, not the one that was just set expect(disconnectSpy).toHaveBeenCalled() }) })
4,143
0
petrpan-code/redwoodjs/redwood/packages/api/src/cache
petrpan-code/redwoodjs/redwood/packages/api/src/cache/__tests__/shared.test.ts
import { createCache, formatCacheKey, InMemoryClient } from '../index' describe('exports', () => { it('exports the client that was passed in', () => { const client = new InMemoryClient() const { cacheClient } = createCache(client) expect(cacheClient).toEqual(client) }) }) describe('formatCacheKey', () => { it('creates a key from a string', () => { expect(formatCacheKey('foobar')).toEqual('foobar') expect(formatCacheKey('foo-bar')).toEqual('foo-bar') }) it('creates a key from an array', () => { expect(formatCacheKey(['foo'])).toEqual('foo') expect(formatCacheKey(['foo', 'bar'])).toEqual('foo-bar') }) it('appends a prefix', () => { expect(formatCacheKey('bar', 'foo')).toEqual('foo-bar') expect(formatCacheKey(['bar'], 'foo')).toEqual('foo-bar') expect(formatCacheKey(['bar', 'baz'], 'foo')).toEqual('foo-bar-baz') }) it('does not append the prefix more than once', () => { expect(formatCacheKey('foo-bar', 'foo')).toEqual('foo-bar') expect(formatCacheKey(['foo', 'bar'], 'foo')).toEqual('foo-bar') // needs a - to match against the prefix expect(formatCacheKey('foobar', 'foo')).toEqual('foo-foobar') }) })
4,151
0
petrpan-code/redwoodjs/redwood/packages/api/src
petrpan-code/redwoodjs/redwood/packages/api/src/logger/logger.test.ts
import { existsSync, readFileSync, statSync } from 'fs' import os from 'os' import { join } from 'path' import split from 'split2' const pid = process.pid const hostname = os.hostname() import { createLogger, emitLogLevels } from '../logger' import type { LoggerOptions, BaseLogger } from '../logger' const once = (emitter, name) => { return new Promise((resolve, reject) => { if (name !== 'error') { emitter.once('error', reject) } emitter.once(name, ({ ...args }) => { emitter.removeListener('error', reject) resolve({ ...args }) }) }) } const sink = () => { const logStatement = split((data) => { try { return JSON.parse(data) } catch (err) { console.log(err) console.log(data) } }) return logStatement } const watchFileCreated = (filename) => { return new Promise((resolve, reject) => { const TIMEOUT = 800 const INTERVAL = 100 const threshold = TIMEOUT / INTERVAL let counter = 0 const interval = setInterval(() => { // On some CI runs file is created but not filled if (existsSync(filename) && statSync(filename).size !== 0) { clearInterval(interval) resolve(null) } else if (counter <= threshold) { counter++ } else { clearInterval(interval) reject(new Error(`${filename} was not created.`)) } }, INTERVAL) }) } const setupLogger = ( loggerOptions?: LoggerOptions, destination?: string, showConfig?: boolean ): { logger: BaseLogger logSinkData?: Promise<unknown> } => { if (destination) { const logger = createLogger({ options: { ...loggerOptions }, destination: destination, showConfig, }) return { logger } } else { const stream = sink() const logSinkData = once(stream, 'data') const logger = createLogger({ options: { ...loggerOptions }, destination: stream, showConfig, }) return { logger, logSinkData } } } describe('logger', () => { describe('creates a logger without options', () => { test('it logs a trace message', async () => { const logger = createLogger({}) expect(logger).toBeDefined() }) }) describe('supports various logging levels', () => { test('it logs a trace message', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.trace('test of a trace level message') const logStatement = await logSinkData expect(logStatement).toHaveProperty('level') expect(logStatement).toHaveProperty('time') expect(logStatement).toHaveProperty('msg') expect(logStatement['level']).toEqual(10) expect(logStatement['msg']).toEqual('test of a trace level message') }) test('it logs an info message', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.info('test of an info level message') const logStatement = await logSinkData expect(logStatement).toHaveProperty('level') expect(logStatement).toHaveProperty('time') expect(logStatement).toHaveProperty('msg') expect(logStatement['level']).toEqual(30) expect(logStatement['msg']).toEqual('test of an info level message') }) test('it logs a debug message', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.debug('test of a debug level message') const logStatement = await logSinkData expect(logStatement).toHaveProperty('level') expect(logStatement).toHaveProperty('time') expect(logStatement).toHaveProperty('msg') expect(logStatement['level']).toEqual(20) expect(logStatement['msg']).toEqual('test of a debug level message') }) test('it logs a warning message', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.warn('test of a warning level message') const logStatement = await logSinkData expect(logStatement).toHaveProperty('level') expect(logStatement).toHaveProperty('time') expect(logStatement).toHaveProperty('msg') expect(logStatement['level']).toEqual(40) expect(logStatement['msg']).toEqual('test of a warning level message') }) test('it logs an error message', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) const error = Object.assign(new Error('TestError'), { message: 'something unexpected happened', }) logger.error({ message: error.message }, 'test of an error level message') const logStatement = await logSinkData expect(logStatement).toHaveProperty('level') expect(logStatement).toHaveProperty('time') expect(logStatement).toHaveProperty('msg') expect(logStatement).toHaveProperty('message') expect(logStatement['level']).toEqual(50) expect(logStatement['msg']).toEqual('test of an error level message') expect(logStatement['message']).toEqual('something unexpected happened') }) }) describe('supports key redaction', () => { test('it redacts defaults header authorization', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace', redact: ['event.headers.authorization'], }) const event = { event: { headers: { authorization: 'Bearer access_token' } }, } logger.info(event, 'test of an access token') const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of an access token') expect(logStatement).toHaveProperty('event') expect(logStatement['event']['headers']['authorization']).toEqual( '[Redacted]' ) }) test('it redacts the value of a given key', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace', redact: ['redactedKey'], }) logger.info({ redactedKey: 'you cannot see me' }, 'test of a redaction') const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redaction') expect(logStatement).toHaveProperty('redactedKey') expect(logStatement['redactedKey']).toEqual('[Redacted]') }) test('it redacts a JWT token key by default', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.info( { jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c', }, 'test of a redacted JWT' ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted JWT') expect(logStatement).toHaveProperty('jwt') expect(logStatement['jwt']).toEqual('[Redacted]') }) test('it redacts a password key by default', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.info( { password: '123456', }, 'test of a redacted password' ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted password') expect(logStatement).toHaveProperty('password') expect(logStatement['password']).toEqual('[Redacted]') }) test('it redacts a hashedPassword key by default', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.info( { hashedPassword: 'c0RnBEEF####', }, 'test of a redacted hashed password' ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted hashed password') expect(logStatement).toHaveProperty('hashedPassword') expect(logStatement['hashedPassword']).toEqual('[Redacted]') }) test('it redacts a hashedPassword key in data by default', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.info( { data: { hashedPassword: 'c0RnBEEF####', }, }, 'test of a redacted data hashed password' ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual( 'test of a redacted data hashed password' ) expect(logStatement).toHaveProperty('data.hashedPassword') expect(logStatement['data']['hashedPassword']).toEqual('[Redacted]') }) test('it redacts a hashedPassword key in user data by default', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.info( { data: { user: { hashedPassword: 'c0RnBEEF####', }, }, }, 'test of a redacted user data hashed password' ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual( 'test of a redacted user data hashed password' ) expect(logStatement).toHaveProperty('data.user.hashedPassword') expect(logStatement['data']['user']['hashedPassword']).toEqual( '[Redacted]' ) }) test('it redacts a salt key by default', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.info( { salt: 'npeppa', }, 'test of a redacted salt' ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted salt') expect(logStatement).toHaveProperty('salt') expect(logStatement['salt']).toEqual('[Redacted]') }) test('it redacts a salt key in data by default', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.info( { data: { salt: 'npeppa', }, }, 'test of a redacted data salt' ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted data salt') expect(logStatement).toHaveProperty('data.salt') expect(logStatement['data']['salt']).toEqual('[Redacted]') }) test('it redacts a salt key in user data by default', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.info( { data: { user: { salt: 'npeppa', }, }, }, 'test of a redacted user data salt' ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted user data salt') expect(logStatement).toHaveProperty('data.user.salt') expect(logStatement['data']['user']['salt']).toEqual('[Redacted]') }) test('it redacts the email key by default', async () => { const { logger, logSinkData } = setupLogger({ level: 'trace' }) logger.info( { email: '[email protected]', }, 'test of a redacted email' ) const logStatement = await logSinkData expect(logStatement['msg']).toEqual('test of a redacted email') expect(logStatement).toHaveProperty('email') expect(logStatement['email']).toEqual('[Redacted]') }) }) describe('file logging', () => { test('it creates a log file with a statement', async () => { const tmp = join( os.tmpdir(), '_' + Math.random().toString(36).substr(2, 9) ) const { logger } = setupLogger({ level: 'trace' }, tmp) logger.warn('logged a warning to a temp file') await watchFileCreated(tmp) const logStatement = JSON.parse(readFileSync(tmp).toString()) delete logStatement.time expect(logStatement).toEqual({ pid, hostname, level: 40, msg: 'logged a warning to a temp file', }) }) }) describe('handles Prisma Logging', () => { test('it defines log levels to emit', () => { const log = emitLogLevels(['info', 'warn', 'error']) expect(log).toEqual([ { emit: 'event', level: 'info' }, { emit: 'event', level: 'warn' }, { emit: 'event', level: 'error' }, ]) }) test('it defines log levels with query events to emit', () => { const log = emitLogLevels(['info', 'warn', 'error', 'query']) expect(log).toEqual([ { emit: 'event', level: 'info' }, { emit: 'event', level: 'warn' }, { emit: 'event', level: 'error' }, { emit: 'event', level: 'query' }, ]) }) }) })
4,156
0
petrpan-code/redwoodjs/redwood/packages/api/src
petrpan-code/redwoodjs/redwood/packages/api/src/webhooks/webhooks.test.ts
import type { APIGatewayProxyEvent } from 'aws-lambda' import { signPayload, verifyEvent, verifySignature, WebhookVerificationError, DEFAULT_WEBHOOK_SIGNATURE_HEADER, } from './index' const payload = 'No more secrets, Marty.' const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' const ONE_MINUTE = 60_000 const TEN_MINUTES = 10 * ONE_MINUTE const FIFTEEN_MINUTES = 15 * ONE_MINUTE // See: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/aws-lambda/trigger/api-gateway-proxy.d.ts const buildEvent = ({ payload, signature = '', signatureHeader = '', isBase64Encoded = false, }): APIGatewayProxyEvent => { const headers = {} headers[signatureHeader.toLocaleLowerCase()] = signature const body = isBase64Encoded ? Buffer.from(payload || '').toString('base64') : payload return { body, headers, multiValueHeaders: {}, isBase64Encoded, path: '', pathParameters: null, stageVariables: null, httpMethod: 'GET', queryStringParameters: null, requestContext: null, resource: null, multiValueQueryStringParameters: null, } } beforeEach(() => { jest.spyOn(console, 'warn').mockImplementation(jest.fn()) }) afterEach(() => { jest.spyOn(console, 'warn').mockRestore() }) describe('webhooks', () => { describe('using the timestampScheme verifier', () => { describe('signs a payload with default timestamp', () => { test('it has a time and scheme signature', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, }) expect(signature).toMatch(/t=(\d+),v1=([\da-f]+)/) }) test('it signs and verifies', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, }) expect( verifySignature('timestampSchemeVerifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the sha1 verifier', () => { describe('signs a payload', () => { test('it has a sha1 signature', () => { const signature = signPayload('sha1Verifier', { payload, secret, }) expect(signature).toMatch(/sha1=([\da-f]+)/) }) test('it signs and verifies', () => { const signature = signPayload('sha1Verifier', { payload, secret, }) expect( verifySignature('sha1Verifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the sha256 verifier', () => { describe('signs a payload', () => { test('it has a sha256 signature', () => { const signature = signPayload('sha256Verifier', { payload, secret, }) expect(signature).toMatch(/sha256=([\da-f]+)/) }) test('it signs and verifies', () => { const signature = signPayload('sha256Verifier', { payload, secret, }) expect( verifySignature('sha256Verifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the secret key verifier', () => { describe('signs a payload', () => { test('it has the key as a signature', () => { const signature = signPayload('secretKeyVerifier', { payload, secret, }) expect(signature).toEqual(secret) }) test('it signs and verifies', () => { const signature = signPayload('secretKeyVerifier', { payload, secret, }) expect( verifySignature('secretKeyVerifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the JWT verifier', () => { describe('signs a payload', () => { test('it has the JWT as a signature', () => { const signature = signPayload('jwtVerifier', { payload, secret, }) expect(signature).toEqual( 'eyJhbGciOiJIUzI1NiJ9.Tm8gbW9yZSBzZWNyZXRzLCBNYXJ0eS4.LBqlEwDa4bWxzrv_Y1_Y7S6_7czhzLZuF17d5c6YjXI' ) }) test('it signs and verifies', () => { const signature = signPayload('jwtVerifier', { payload, secret, }) expect( verifySignature('jwtVerifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the base64 sha1 verifier', () => { describe('signs a payload', () => { test('it signs and verifies', () => { const signature = signPayload('base64Sha1Verifier', { payload, secret, }) expect( verifySignature('base64Sha1Verifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('using the base64 sha256 verifier', () => { describe('signs a payload', () => { test('it has a base64 sha256 signature', () => { const body = '{"data": {"abandon_at": 1648585920141, ' + '"client_id": "client_25hz3vm5USqCG3a7jMXqdjzjJyK", ' + '"created_at": 1645993920141, "expire_at": 1646598720141, ' + '"id": "sess_25hz5CxFyrNJgDO1TY52LGPtM0e", ' + '"last_active_at": 1645993920141, "object": "session", ' + '"status": "active", "updated_at": 1645993920149, ' + '"user_id": "user_25h1zRMh7owJp6us0Sqs3UXwW0y"}, ' + '"object": "event", "type": "session.created"}' const payload = `msg_25hz5cPxRz5ilWSQSiYfgxpYHTH.1646004463.${body}` const secret = 'MY_VOICE_IS_MY_PASSPORT_VERIFY_ME' const signature = signPayload('base64Sha256Verifier', { payload, secret, }) expect(signature).toMatch( 'AaP4EgcpPC5oE3eppI/s6EMtQCZ4Ap34wNHPoxBoikI=' ) }) test('it signs and verifies', () => { const signature = signPayload('base64Sha256Verifier', { payload, secret, }) expect( verifySignature('base64Sha256Verifier', { payload, secret, signature, }) ).toBeTruthy() }) }) }) describe('webhooks via event', () => { describe('when it receives an event it extracts the signature and payload from the event', () => { test('it can verify an event body payload with a signature it generates', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect( verifyEvent('timestampSchemeVerifier', { event, secret }) ).toBeTruthy() }) test('it can verify an event base64encoded body payload with a signature it generates', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, isBase64Encoded: true, }) expect( verifyEvent('timestampSchemeVerifier', { event, secret }) ).toBeTruthy() }) test('it can verify overriding the event body payload with a signature it generates', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, }) const event = buildEvent({ payload: { body: payload }, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect( verifyEvent('timestampSchemeVerifier', { event, payload, secret, }) ).toBeTruthy() }) test('it denies verification when signed with a different secret', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret: 'WERNER_BRANDES', }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect(() => { verifyEvent('timestampSchemeVerifier', { event, secret }) }).toThrow(WebhookVerificationError) }) test('it verifies when within the timestamp tolerance', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, options: { currentTimestampOverride: Date.now() - TEN_MINUTES }, }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect(() => { verifyEvent('timestampSchemeVerifier', { event, secret, options: { tolerance: FIFTEEN_MINUTES }, }) }).toBeTruthy() }) test('it denies verification when verifying with a short tolerance', () => { const signature = signPayload('timestampSchemeVerifier', { payload, secret, options: { currentTimestampOverride: Date.now() - TEN_MINUTES }, }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect(() => { verifyEvent('timestampSchemeVerifier', { event, secret, options: { tolerance: 5_000 }, }) }).toThrow(WebhookVerificationError) }) test('it denies verification when verifying with a short tolerance also for sha1 verifier', () => { const signature = signPayload('sha1Verifier', { payload, secret, }) const event = buildEvent({ payload, signature, signatureHeader: DEFAULT_WEBHOOK_SIGNATURE_HEADER, }) expect(() => { verifyEvent('sha1Verifier', { event, secret, options: { eventTimestamp: Date.now(), currentTimestampOverride: Date.now() - FIFTEEN_MINUTES, tolerance: ONE_MINUTE, }, }) }).toThrow(WebhookVerificationError) }) }) describe('provider specific tests', () => { test('clerk', () => { const body = '{"data": {"abandon_at": 1648585920141, ' + '"client_id": "client_25hz3vm5USqCG3a7jMXqdjzjJyK", ' + '"created_at": 1645993920141, "expire_at": 1646598720141, ' + '"id": "sess_25hz5CxFyrNJgDO1TY52LGPtM0e", ' + '"last_active_at": 1645993920141, "object": "session", ' + '"status": "active", "updated_at": 1645993920149, ' + '"user_id": "user_25h1zRMh7owJp6us0Sqs3UXwW0y"}, ' + '"object": "event", "type": "session.created"}' const event = buildEvent({ payload: body }) event.headers = { 'svix-signature': 'v1,AaP4EgcpPC5oE3eppI/s6EMtQCZ4Ap34wNHPoxBoikI=', 'svix-timestamp': '1646004463', 'svix-id': 'msg_25hz5cPxRz5ilWSQSiYfgxpYHTH', } const svix_id = event.headers['svix-id'] const svix_timestamp = event.headers['svix-timestamp'] const payload = `${svix_id}.${svix_timestamp}.${event.body}` const secret = 'whsec_MY_VOICE_IS_MY_PASSPORT_VERIFY_ME'.slice(6) expect( verifyEvent('base64Sha256Verifier', { event, secret, payload, options: { signatureHeader: 'svix-signature', signatureTransformer: (signature: string) => { // Clerk can pass a space separated list of signatures. // Let's just use the first one that's of version 1 const passedSignatures = signature.split(' ') for (const versionedSignature of passedSignatures) { const [version, signature] = versionedSignature.split(',') if (version === 'v1') { return signature } } }, eventTimestamp: parseInt(svix_timestamp, 10) * 1000, // One minute from the event's timestamp is within the default // tolerance of five minutes currentTimestampOverride: parseInt(svix_timestamp, 10) * 1000 - ONE_MINUTE, }, }) ).toBeTruthy() }) }) }) })
4,166
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/auth0/api/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/auth0/api/src/__tests__/auth0.test.ts
import jwt from 'jsonwebtoken' import { verifyAuth0Token } from '../decoder' jest.mock('jsonwebtoken', () => ({ verify: jest.fn(), decode: jest.fn(), })) test('verify, and not decode, should be called in production', () => { const { NODE_ENV } = process.env process.env.NODE_ENV = 'production' process.env.AUTH0_DOMAIN = 'redwoodjs.com' process.env.AUTH0_AUDIENCE = 'michael bolton' verifyAuth0Token('token') expect(jwt.decode).not.toBeCalled() expect(jwt.verify).toBeCalled() process.env.NODE_ENV = NODE_ENV })
4,175
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/auth0/setup/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/auth0/setup/src/__tests__/setup.test.ts
import { command, description, builder, handler } from '../setup' // mock Telemetry for CLI commands so they don't try to spawn a process jest.mock('@redwoodjs/telemetry', () => { return { errorTelemetry: () => jest.fn(), timedTelemetry: () => jest.fn(), } }) test('standard exports', () => { expect(command).toEqual('auth0') expect(description).toMatch(/Auth0/) expect(typeof builder).toEqual('function') expect(typeof handler).toEqual('function') })
4,185
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/auth0/web/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/auth0/web/src/__tests__/auth0.test.tsx
import type { Auth0Client, GetTokenSilentlyOptions, GetTokenSilentlyVerboseResponse, User, } from '@auth0/auth0-spa-js' import { renderHook, act } from '@testing-library/react' import type { CurrentUser } from '@redwoodjs/auth' import { createAuth } from '../auth0' const user: User = { sub: 'unique_user_id', name: 'John', email: '[email protected]', roles: ['user'], } const adminUser: User = { sub: 'unique_user_id_admin', name: 'Mr Smith', email: '[email protected]', roles: ['user', 'admin'], } let loggedInUser: User | undefined async function getTokenSilently( options: GetTokenSilentlyOptions & { detailedResponse: true } ): Promise<GetTokenSilentlyVerboseResponse> async function getTokenSilently( options?: GetTokenSilentlyOptions ): Promise<string> async function getTokenSilently(): Promise< string | GetTokenSilentlyVerboseResponse > { return 'token' } const auth0MockClient: Partial<Auth0Client> = { handleRedirectCallback: async () => ({}), loginWithRedirect: async () => { loggedInUser = user }, logout: async () => {}, getTokenSilently, getUser: <TUser extends User>() => { return new Promise<TUser | undefined>((resolve) => { resolve((loggedInUser as TUser) || undefined) }) }, } const fetchMock = jest.fn() fetchMock.mockImplementation(async (_url, options) => { const body = options?.body ? JSON.parse(options.body) : {} if ( body.query === 'query __REDWOOD__AUTH_GET_CURRENT_USER { redwood { currentUser } }' ) { return { ok: true, text: () => '', json: () => ({ data: { redwood: { currentUser: loggedInUser } } }), } } return { ok: true, text: () => '', json: () => ({}) } }) beforeAll(() => { global.fetch = fetchMock }) beforeEach(() => { fetchMock.mockClear() loggedInUser = undefined }) function getAuth0Auth(customProviderHooks?: { useCurrentUser?: () => Promise<CurrentUser> useHasRole?: ( currentUser: CurrentUser | null ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( auth0MockClient as Auth0Client, customProviderHooks ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, }) return result } describe('auth0Auth', () => { it('is not authenticated before logging in', async () => { const auth = getAuth0Auth().current await act(async () => { expect(auth.isAuthenticated).toBeFalsy() }) }) it('is authenticated after logging in', async () => { const authRef = getAuth0Auth() await act(async () => { authRef.current.logIn() }) expect(authRef.current.isAuthenticated).toBeTruthy() }) it('is not authenticated after logging out', async () => { const authRef = getAuth0Auth() await act(async () => { authRef.current.logIn() }) expect(authRef.current.isAuthenticated).toBeTruthy() await act(async () => { authRef.current.logOut() }) expect(authRef.current.isAuthenticated).toBeFalsy() }) it('has role "user"', async () => { const authRef = getAuth0Auth() expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() }) it('has role "admin"', async () => { const authRef = getAuth0Auth() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { authRef.current.logIn() loggedInUser = adminUser }) expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom hasRole function', async () => { function useHasRole(currentUser: CurrentUser | null) { return (rolesToCheck: string | string[]) => { if (!currentUser || typeof rolesToCheck !== 'string') { return false } if (rolesToCheck === 'user') { // Everyone has role "user" return true } // For the admin role we check their email address if ( rolesToCheck === 'admin' && currentUser.email === '[email protected]' ) { return true } return false } } const authRef = getAuth0Auth({ useHasRole }) expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { authRef.current.logIn() loggedInUser = adminUser }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom getCurrentUser function', async () => { async function useCurrentUser() { return { ...loggedInUser, roles: ['custom-current-user'], } } const authRef = getAuth0Auth({ useCurrentUser }) // Need to be logged in, otherwise getCurrentUser won't be invoked await act(async () => { authRef.current.logIn() }) await act(async () => { expect(authRef.current.hasRole('user')).toBeFalsy() expect(authRef.current.hasRole('custom-current-user')).toBeTruthy() }) }) })
4,193
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/azureActiveDirectory/api/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/azureActiveDirectory/api/src/__tests__/azureActiveDirectory.test.ts
import type { APIGatewayProxyEvent, Context as LambdaContext } from 'aws-lambda' import jwt from 'jsonwebtoken' import { authDecoder } from '../decoder' jest.mock('jsonwebtoken', () => ({ verify: jest.fn(), decode: jest.fn(), })) const req = { event: {} as APIGatewayProxyEvent, context: {} as LambdaContext, } let consoleError beforeAll(() => { consoleError = console.error console.error = () => {} }) afterAll(() => { console.error = consoleError }) test('returns null for unsupported type', async () => { const decoded = await authDecoder('token', 'netlify', req) expect(decoded).toBe(null) }) test('throws if AZURE_ACTIVE_DIRECTORY_AUTHORITY env var is not set', async () => { delete process.env.AZURE_ACTIVE_DIRECTORY_AUTHORITY process.env.AZURE_ACTIVE_DIRECTORY_JTW_ISSUER = 'jwt-issuer' await expect( authDecoder('token', 'azureActiveDirectory', req) ).rejects.toThrow('AZURE_ACTIVE_DIRECTORY_AUTHORITY env var is not set') }) describe('invoking in prod', () => { let NODE_ENV beforeAll(() => { NODE_ENV = process.env.NODE_ENV process.env.AZURE_ACTIVE_DIRECTORY_AUTHORITY = 'authority' process.env.AZURE_ACTIVE_DIRECTORY_JTW_ISSUER = 'jwt-issuer' }) afterAll(() => { process.env.NODE_ENV = NODE_ENV }) test('verify, not decode, is called in production', async () => { process.env.NODE_ENV = 'production' authDecoder('token', 'azureActiveDirectory', req) expect(jwt.decode).not.toBeCalled() expect(jwt.verify).toBeCalled() }) })
4,202
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/azureActiveDirectory/setup/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/azureActiveDirectory/setup/src/__tests__/setup.test.ts
import { command, description, builder, handler } from '../setup' // mock Telemetry for CLI commands so they don't try to spawn a process jest.mock('@redwoodjs/telemetry', () => { return { errorTelemetry: () => jest.fn(), timedTelemetry: () => jest.fn(), } }) test('standard exports', () => { expect(command).toEqual('azure-active-directory') expect(description).toMatch(/Azure Active Directory/) expect(typeof builder).toEqual('function') expect(typeof handler).toEqual('function') })
4,212
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/azureActiveDirectory/web/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/azureActiveDirectory/web/src/__tests__/azureActiveDirectory.test.tsx
import type { AccountInfo, PublicClientApplication as AzureActiveDirectoryClient, RedirectRequest, } from '@azure/msal-browser' import { renderHook, act } from '@testing-library/react' import type { CurrentUser } from '@redwoodjs/auth' import { createAuth } from '../azureActiveDirectory' const user: AccountInfo = { name: 'John', username: '[email protected]', idTokenClaims: { roles: ['user'], }, homeAccountId: 'home_account_id', environment: 'environment', tenantId: 'tenant_id', localAccountId: 'local_account_id', } const adminUser: AccountInfo = { name: 'Mr Smith', username: '[email protected]', idTokenClaims: { roles: ['user', 'admin'], }, homeAccountId: 'home_account_id', environment: 'environment', tenantId: 'tenant_id', localAccountId: 'local_account_id', } let loggedInUser: AccountInfo | null = null const defaultToken = () => ({ authority: 'authority', uniqueId: 'unique_id', tenantId: 'tenant_id', scopes: ['scope'], account: { homeAccountId: 'home_account_id', environment: 'environment', tenantId: 'tenant_id', username: loggedInUser?.username || '', localAccountId: 'local_account_id', }, idToken: 'id_token', idTokenClaims: {}, accessToken: 'access_token', fromCache: true, expiresOn: new Date(), tokenType: 'jwt', correlationId: 'correlation_id', }) const azureActiveDirectoryMockClient: Partial<AzureActiveDirectoryClient> = { loginRedirect: async (options?: RedirectRequest) => { const claims = JSON.parse(options?.claims || '{}') if (claims.accessToken?.find((token) => token.name === 'role')) { loggedInUser = adminUser } else { loggedInUser = user } }, logoutRedirect: async () => { loggedInUser = null }, acquireTokenSilent: async () => { return defaultToken() }, getActiveAccount: () => loggedInUser, handleRedirectPromise: async () => defaultToken(), getAllAccounts: () => (loggedInUser ? [loggedInUser] : []), setActiveAccount: (account: AccountInfo | null) => { loggedInUser = account }, } const fetchMock = jest.fn() fetchMock.mockImplementation(async (_url, options) => { const body = options?.body ? JSON.parse(options.body) : {} if ( body.query === 'query __REDWOOD__AUTH_GET_CURRENT_USER { redwood { currentUser } }' ) { return { ok: true, text: () => '', json: () => ({ data: { redwood: { currentUser: { ...loggedInUser, roles: loggedInUser?.idTokenClaims?.roles, }, }, }, }), } } return { ok: true, text: () => '', json: () => ({}) } }) beforeAll(() => { globalThis.fetch = fetchMock }) beforeEach(() => { fetchMock.mockClear() loggedInUser = null }) function getAzureActiveDirectoryAuth(customProviderHooks?: { useCurrentUser?: () => Promise<CurrentUser> useHasRole?: ( currentUser: CurrentUser | null ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( azureActiveDirectoryMockClient as AzureActiveDirectoryClient, customProviderHooks ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, }) return result } describe('azureActiveDirectoryAuth', () => { it('is not authenticated before logging in', async () => { const auth = getAzureActiveDirectoryAuth().current await act(async () => { expect(auth.isAuthenticated).toBeFalsy() }) }) it('is authenticated after logging in', async () => { const authRef = getAzureActiveDirectoryAuth() await act(async () => { authRef.current.logIn() }) expect(authRef.current.isAuthenticated).toBeTruthy() }) it('is not authenticated after logging out', async () => { const authRef = getAzureActiveDirectoryAuth() await act(async () => { authRef.current.logIn() }) expect(authRef.current.isAuthenticated).toBeTruthy() await act(async () => { authRef.current.logOut() }) expect(authRef.current.isAuthenticated).toBeFalsy() }) it('has role "user"', async () => { const authRef = getAzureActiveDirectoryAuth() expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() }) it('has role "admin"', async () => { const authRef = getAzureActiveDirectoryAuth() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { const claimsRequest = { idToken: [ { name: 'name', essential: true }, { name: 'email', essential: true }, { name: 'country', essential: false }, ], accessToken: [ { name: 'role', essential: true }, { name: 'permissions', essential: true }, ], } authRef.current.logIn({ scopes: ['openid', 'profile'], claims: JSON.stringify(claimsRequest), }) }) expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom hasRole function', async () => { function useHasRole(currentUser: CurrentUser | null) { return (rolesToCheck: string | string[]) => { if (!currentUser || typeof rolesToCheck !== 'string') { return false } if (rolesToCheck === 'user') { // Everyone has role "user" return true } // For the admin role we check their email address if ( rolesToCheck === 'admin' && currentUser.username === '[email protected]' ) { return true } return false } } const authRef = getAzureActiveDirectoryAuth({ useHasRole }) expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { authRef.current.logIn() loggedInUser = adminUser }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom getCurrentUser function', async () => { async function useCurrentUser() { return { ...loggedInUser, roles: ['custom-current-user'], } } const authRef = getAzureActiveDirectoryAuth({ useCurrentUser }) // Need to be logged in, otherwise getCurrentUser won't be invoked await act(async () => { authRef.current.logIn() }) await act(async () => { expect(authRef.current.hasRole('user')).toBeFalsy() expect(authRef.current.hasRole('custom-current-user')).toBeTruthy() }) }) })
4,220
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/clerk/api/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/clerk/api/src/__tests__/clerk.test.ts
import type { APIGatewayProxyEvent, Context as LambdaContext } from 'aws-lambda' import { authDecoder, clerkAuthDecoder } from '../decoder' const req = { event: {} as APIGatewayProxyEvent, context: {} as LambdaContext, } let consoleError beforeAll(() => { consoleError = console.error console.error = () => {} }) afterAll(() => { console.error = consoleError }) describe('deprecated authDecoder', () => { test('returns null for unsupported type', async () => { const decoded = await authDecoder('token', 'netlify', req) expect(decoded).toBe(null) }) test('rejects when the token is invalid', async () => { process.env.CLERK_JWT_KEY = 'jwt-key' await expect(authDecoder('invalid-token', 'clerk', req)).rejects.toThrow() }) }) describe('clerkAuthDecoder', () => { test('returns null for unsupported type', async () => { const decoded = await clerkAuthDecoder('token', 'netlify', req) expect(decoded).toBe(null) }) test('rejects when the token is invalid', async () => { process.env.CLERK_JWT_KEY = 'jwt-key' await expect( clerkAuthDecoder('invalid-token', 'clerk', req) ).rejects.toThrow() }) })
4,238
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/clerk/web/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/clerk/web/src/__tests__/clerk.test.tsx
import type { Clerk as ClerkClient, UserResource, EmailAddressResource, ActiveSessionResource, } from '@clerk/types' import { renderHook, act } from '@testing-library/react' import type { CurrentUser } from '@redwoodjs/auth' import { createAuth } from '../clerk' const user: Partial<UserResource> = { id: 'unique_user_id', fullName: 'John Doe', emailAddresses: [ { id: 'email_id', emailAddress: '[email protected]', } as EmailAddressResource, ], publicMetadata: { roles: ['user'], }, } const adminUser: Partial<UserResource> = { id: 'unique_user_id_admin', fullName: 'Mr Smith', emailAddresses: [ { id: 'email_id', emailAddress: '[email protected]', } as EmailAddressResource, ], publicMetadata: { roles: ['user', 'admin'], }, } let loggedInUser: Partial<UserResource> | undefined const clerkMockClient: Partial<ClerkClient> = { openSignIn: () => { loggedInUser ||= user }, openSignUp: () => { loggedInUser = user }, signOut: async () => { loggedInUser = undefined return undefined }, session: { getToken: async () => 'token', } as ActiveSessionResource, addListener: () => { // Unsubscribe callback return () => {} }, get user() { return loggedInUser as UserResource | undefined }, } const fetchMock = jest.fn() fetchMock.mockImplementation(async (_url, options) => { const body = options?.body ? JSON.parse(options.body) : {} if ( body.query === 'query __REDWOOD__AUTH_GET_CURRENT_USER { redwood { currentUser } }' ) { return { ok: true, text: () => '', json: () => ({ data: { redwood: { currentUser: { ...loggedInUser, roles: loggedInUser?.publicMetadata?.roles, }, }, }, }), } } return { ok: true, text: () => '', json: () => ({}) } }) beforeAll(() => { globalThis.fetch = fetchMock globalThis.Clerk = clerkMockClient }) beforeEach(() => { fetchMock.mockClear() loggedInUser = undefined }) function getClerkAuth(customProviderHooks?: { useCurrentUser?: () => Promise<CurrentUser> useHasRole?: ( currentUser: CurrentUser | null ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth(customProviderHooks) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, }) return result } describe('Clerk', () => { it('is not authenticated before logging in', async () => { const auth = getClerkAuth().current await act(async () => { expect(auth.isAuthenticated).toBeFalsy() }) }) it('is authenticated after logging in', async () => { const authRef = getClerkAuth() await act(async () => { authRef.current.logIn() }) expect(authRef.current.isAuthenticated).toBeTruthy() }) it('is not authenticated after logging out', async () => { const authRef = getClerkAuth() await act(async () => { authRef.current.logIn() }) expect(authRef.current.isAuthenticated).toBeTruthy() await act(async () => { authRef.current.logOut() }) expect(authRef.current.isAuthenticated).toBeFalsy() }) it('has role "user"', async () => { const authRef = getClerkAuth() expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() }) it('has role "admin"', async () => { const authRef = getClerkAuth() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { loggedInUser = adminUser authRef.current.logIn() }) expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom hasRole function', async () => { function useHasRole(currentUser: CurrentUser | null) { return (rolesToCheck: string | string[]) => { if (!currentUser || typeof rolesToCheck !== 'string') { return false } if (rolesToCheck === 'user') { // Everyone has role "user" return true } // For the admin role we check their email address if ( rolesToCheck === 'admin' && (currentUser.emailAddresses as any).some( (email) => email.emailAddress === '[email protected]' ) ) { return true } return false } } const authRef = getClerkAuth({ useHasRole }) expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { loggedInUser = adminUser authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom getCurrentUser function', async () => { async function useCurrentUser() { return { ...loggedInUser, roles: ['custom-current-user'], } } const authRef = getClerkAuth({ useCurrentUser }) // Need to be logged in, otherwise getCurrentUser won't be invoked await act(async () => { authRef.current.logIn() }) await act(async () => { expect(authRef.current.hasRole('user')).toBeFalsy() expect(authRef.current.hasRole('custom-current-user')).toBeTruthy() }) }) })
4,247
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/custom/setup/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/custom/setup/src/__tests__/setup.test.ts
import { command, description, builder, handler } from '../setup' // mock Telemetry for CLI commands so they don't try to spawn a process jest.mock('@redwoodjs/telemetry', () => { return { errorTelemetry: () => jest.fn(), timedTelemetry: () => jest.fn(), } }) test('standard exports', () => { expect(command).toEqual('custom') expect(description).toMatch(/custom auth/) expect(typeof builder).toEqual('function') expect(typeof handler).toEqual('function') })
4,261
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/dbAuth/api/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/dbAuth/api/src/__tests__/shared.test.ts
import crypto from 'node:crypto' import path from 'node:path' import type { APIGatewayProxyEvent } from 'aws-lambda' import * as error from '../errors' import { extractCookie, getSession, cookieName, hashPassword, isLegacySession, legacyHashPassword, decryptSession, dbAuthSession, webAuthnSession, extractHashingOptions, } from '../shared' const FIXTURE_PATH = path.resolve( __dirname, '../../../../../../__fixtures__/example-todo-main' ) const SESSION_SECRET = '540d03ebb00b441f8f7442cbc39958ad' const encrypt = (data) => { const iv = crypto.randomBytes(16) const cipher = crypto.createCipheriv( 'aes-256-cbc', SESSION_SECRET.substring(0, 32), iv ) let encryptedSession = cipher.update(data, 'utf-8', 'base64') encryptedSession += cipher.final('base64') return `${encryptedSession}|${iv.toString('base64')}` } function dummyEvent(cookie?: string) { return { headers: { cookie, }, } as unknown as APIGatewayProxyEvent } beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) describe('getSession()', () => { it('returns null if no text', () => { expect(getSession(undefined, 'session')).toEqual(null) }) it('returns null if no session cookie', () => { expect(getSession('foo=bar', 'session')).toEqual(null) }) it('returns the value of the session cookie', () => { expect(getSession('session_8911=qwerty', 'session_%port%')).toEqual( 'qwerty' ) }) it('returns the value of the session cookie when there are multiple cookies', () => { expect(getSession('foo=bar;session=qwerty', 'session')).toEqual('qwerty') expect(getSession('session=qwerty;foo=bar', 'session')).toEqual('qwerty') }) it('returns the value of the session cookie when there are multiple cookies separated by spaces (iOS Safari)', () => { expect(getSession('foo=bar; session=qwerty', 'session')).toEqual('qwerty') expect(getSession('session=qwerty; foo=bar', 'session')).toEqual('qwerty') }) }) describe('cookieName()', () => { it('returns the default cookie name', () => { expect(cookieName(undefined)).toEqual('session') }) it('allows you to pass a cookie name to use', () => { expect(cookieName('my_cookie_name')).toEqual('my_cookie_name') }) it('replaces %port% with a port number', () => { expect(cookieName('session_%port%_my_app')).toEqual('session_8911_my_app') }) }) describe('isLegacySession()', () => { it('returns `true` if the session cookie appears to be encrypted with CryptoJS', () => { expect( isLegacySession('U2FsdGVkX1+s7seQJnVgGgInxuXm13l8VvzA3Mg2fYg=') ).toEqual(true) }) it('returns `false` if the session cookie appears to be encrypted with node:crypto', () => { expect( isLegacySession( 'ko6iXKV11DSjb6kFJ4iwcf1FEqa5wPpbL1sdtKiV51Y=|cQaYkOPG/r3ILxWiFiz90w==' ) ).toEqual(false) }) }) describe('decryptSession()', () => { beforeEach(() => { process.env.SESSION_SECRET = SESSION_SECRET }) it('returns an empty array if no session', () => { expect(decryptSession(null)).toEqual([]) }) it('returns an empty array if session is empty', () => { expect(decryptSession('')).toEqual([]) expect(decryptSession(' ')).toEqual([]) }) it('throws an error if decryption errors out', () => { expect(() => decryptSession('session=qwerty')).toThrow( error.SessionDecryptionError ) }) it('returns an array with contents of encrypted cookie parts', () => { const first = { foo: 'bar' } const second = 'abcd' const text = encrypt(JSON.stringify(first) + ';' + second) expect(decryptSession(text)).toEqual([first, second]) }) it('decrypts a session cookie that was created with the legacy CryptoJS algorithm', () => { process.env.SESSION_SECRET = 'QKxN2vFSHAf94XYynK8LUALfDuDSdFowG6evfkFX8uszh4YZqhTiqEdshrhWbwbw' const [json] = decryptSession( 'U2FsdGVkX1+s7seQJnVgGgInxuXm13l8VvzA3Mg2fYg=' ) expect(json).toEqual({ id: 7 }) }) }) describe('dbAuthSession()', () => { beforeEach(() => { process.env.SESSION_SECRET = SESSION_SECRET }) it('returns null if no cookies', () => { expect(dbAuthSession(dummyEvent(), 'session_%port%')).toEqual(null) }) it('return session given event', () => { const first = { foo: 'bar' } const second = 'abcd' const text = encrypt(JSON.stringify(first) + ';' + second) const event = dummyEvent(`session_8911=${text}`) expect(dbAuthSession(event, 'session_%port%')).toEqual(first) }) }) describe('webAuthnSession', () => { it('returns null if no cookies', () => { expect(webAuthnSession(dummyEvent())).toEqual(null) }) it('returns the webAuthn cookie data', () => { const output = webAuthnSession( dummyEvent('session=abcd1234;webAuthn=zyxw9876') ) expect(output).toEqual('zyxw9876') }) }) describe('hashPassword', () => { it('hashes a password with a given salt and returns both', () => { const [hash, salt] = hashPassword('password', { salt: 'ba8b7807c6de6d6a892ef27f4073c603', }) expect(hash).toEqual( '230847bea5154b6c7d281d09593ad1be26fa03a93c04a73bcc2b608c073a8213|16384|8|1' ) expect(salt).toEqual('ba8b7807c6de6d6a892ef27f4073c603') }) it('hashes a password with a generated salt if none provided', () => { const [hash, salt] = hashPassword('password') expect(hash).toMatch(/^[a-f0-9]+|16384|8|1$/) expect(hash.length).toEqual(74) expect(salt).toMatch(/^[a-f0-9]+$/) expect(salt.length).toEqual(64) }) it('normalizes strings so utf-8 variants hash to the same output', () => { const salt = crypto.randomBytes(32).toString('hex') const [hash1] = hashPassword('\u0041\u006d\u00e9\u006c\u0069\u0065', { salt, }) // AmΓ©lie const [hash2] = hashPassword('\u0041\u006d\u0065\u0301\u006c\u0069\u0065', { salt, }) // AmΓ©lie but separate e and accent codepoints expect(hash1).toEqual(hash2) }) it('encodes the scrypt difficulty options into the hash', () => { const [hash] = hashPassword('password', { options: { cost: 8192, blockSize: 16, parallelization: 2 }, }) const [_hash, cost, blockSize, parallelization] = hash.split('|') expect(cost).toEqual('8192') expect(blockSize).toEqual('16') expect(parallelization).toEqual('2') }) }) describe('legacyHashPassword', () => { it('hashes a password with CryptoJS given a salt and returns both', () => { const [hash, salt] = legacyHashPassword( 'password', '2ef27f4073c603ba8b7807c6de6d6a89' ) expect(hash).toEqual( '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba' ) expect(salt).toEqual('2ef27f4073c603ba8b7807c6de6d6a89') }) it('hashes a password with a generated salt if none provided', () => { const [hash, salt] = legacyHashPassword('password') expect(hash).toMatch(/^[a-f0-9]+$/) expect(hash.length).toEqual(64) expect(salt).toMatch(/^[a-f0-9]+$/) expect(salt.length).toEqual(64) }) }) describe('session cookie extraction', () => { let event const encryptToCookie = (data) => { return `session=${encrypt(data)}` } beforeEach(() => { event = { queryStringParameters: {}, path: '/.redwood/functions/auth', headers: {}, } }) it('extracts from the event', () => { const cookie = encryptToCookie( JSON.stringify({ id: 9999999999 }) + ';' + 'token' ) event = { headers: { cookie, }, } expect(extractCookie(event)).toEqual(cookie) }) it('extract cookie handles non-JSON event body', () => { event.body = '' expect(extractCookie(event)).toBeUndefined() }) describe('when in development', () => { const curNodeEnv = process.env.NODE_ENV beforeAll(() => { // Session cookie from graphiQLHeaders only extracted in dev process.env.NODE_ENV = 'development' }) afterAll(() => { process.env.NODE_ENV = curNodeEnv event = {} expect(process.env.NODE_ENV).toBe('test') }) it('extract cookie handles non-JSON event body', () => { event.body = '' expect(extractCookie(event)).toBeUndefined() }) it('extracts GraphiQL cookie from the header extensions', () => { const dbUserId = 42 const cookie = encryptToCookie(JSON.stringify({ id: dbUserId })) event.body = JSON.stringify({ extensions: { headers: { 'auth-provider': 'dbAuth', cookie, authorization: 'Bearer ' + dbUserId, }, }, }) expect(extractCookie(event)).toEqual(cookie) }) it('overwrites cookie with event header GraphiQL when in dev', () => { const sessionCookie = encryptToCookie( JSON.stringify({ id: 9999999999 }) + ';' + 'token' ) event = { headers: { cookie: sessionCookie, }, } const dbUserId = 42 const cookie = encryptToCookie(JSON.stringify({ id: dbUserId })) event.body = JSON.stringify({ extensions: { headers: { 'auth-provider': 'dbAuth', cookie, authorization: 'Bearer ' + dbUserId, }, }, }) expect(extractCookie(event)).toEqual(cookie) }) }) }) describe('extractHashingOptions()', () => { it('returns an empty object if no options', () => { expect(extractHashingOptions('')).toEqual({}) expect( extractHashingOptions( '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba' ) ).toEqual({}) expect( extractHashingOptions( '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba|1' ) ).toEqual({}) expect( extractHashingOptions( '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba|1|2' ) ).toEqual({}) }) it('returns an object with scrypt options', () => { expect( extractHashingOptions( '0c2b24e20ee76a887eac1415cc2c175ff961e7a0f057cead74789c43399dd5ba|16384|8|1' ) ).toEqual({ cost: 16384, blockSize: 8, parallelization: 1, }) }) })
4,287
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/dbAuth/web/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/dbAuth/web/src/__tests__/dbAuth.test.ts
import { renderHook, act } from '@testing-library/react' import type { CurrentUser } from '@redwoodjs/auth' import type { DbAuthClientArgs } from '../dbAuth' import { createDbAuthClient, createAuth } from '../dbAuth' globalThis.RWJS_API_URL = '/.redwood/functions' globalThis.RWJS_API_GRAPHQL_URL = '/.redwood/functions/graphql' jest.mock('@whatwg-node/fetch', () => { return }) interface User { username: string email: string roles?: string[] } let loggedInUser: User | undefined const fetchMock = jest.fn() fetchMock.mockImplementation(async (url, options) => { const body = options?.body ? JSON.parse(options.body) : {} if (url?.includes('method=getToken')) { return { ok: true, text: () => (loggedInUser ? 'token' : ''), json: () => ({}), } } if (body.method === 'login') { loggedInUser = { username: body.username, roles: ['user'], email: body.username, } return { ok: true, text: () => '', json: () => loggedInUser, } } if (body.method === 'logout') { loggedInUser = undefined return { ok: true, text: () => '', json: () => ({}), } } if ( body.query === 'query __REDWOOD__AUTH_GET_CURRENT_USER { redwood { currentUser } }' ) { return { ok: true, text: () => '', json: () => ({ data: { redwood: { currentUser: loggedInUser } } }), } } return { ok: true, text: () => '', json: () => ({}) } }) beforeAll(() => { globalThis.fetch = fetchMock }) beforeEach(() => { fetchMock.mockClear() loggedInUser = undefined }) const defaultArgs: DbAuthClientArgs & { useCurrentUser?: () => Promise<CurrentUser> useHasRole?: ( currentUser: CurrentUser | null ) => (rolesToCheck: string | string[]) => boolean } = { fetchConfig: { credentials: 'include' }, } function getDbAuth(args = defaultArgs) { const dbAuthClient = createDbAuthClient(args) const { useAuth, AuthProvider } = createAuth(dbAuthClient, { useHasRole: args.useHasRole, useCurrentUser: args.useCurrentUser, }) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, }) return result } describe('dbAuth', () => { it('sets a default credentials value if not included', async () => { const authRef = getDbAuth({ fetchConfig: {} }) // act is okay here // https://egghead.io/lessons/jest-fix-the-not-wrapped-in-act-warning-when-testing-custom-hooks // plus, we're note rendering anything, so there is nothing to use // `screen.getByText()` etc with to wait for await act(async () => { await authRef.current.getToken() }) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth?method=getToken`, { credentials: 'same-origin', } ) }) it('passes through fetchOptions to forgotPassword calls', async () => { const auth = getDbAuth().current await act(async () => await auth.forgotPassword('username')) expect(fetchMock).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', }) ) }) it('passes through fetchOptions to getToken calls', async () => { const auth = getDbAuth().current await act(async () => { await auth.getToken() }) expect(fetchMock).toHaveBeenCalledTimes(1) expect(fetchMock).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth?method=getToken`, { credentials: 'include', } ) }) it('passes through fetchOptions to login calls', async () => { const auth = (await getDbAuth()).current await act( async () => await auth.logIn({ username: 'username', password: 'password' }) ) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', }) ) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', }) ) }) it('passes through fetchOptions to logout calls', async () => { const auth = getDbAuth().current await act(async () => { await auth.logOut() }) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', }) ) }) it('passes through fetchOptions to resetPassword calls', async () => { const auth = getDbAuth().current await act( async () => await auth.resetPassword({ resetToken: 'reset-token', password: 'password', }) ) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', }) ) }) it('passes through fetchOptions to signup calls', async () => { const auth = getDbAuth().current await act( async () => await auth.signUp({ username: 'username', password: 'password', }) ) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', }) ) }) it('passes through fetchOptions to validateResetToken calls', async () => { const auth = getDbAuth().current await act(async () => await auth.validateResetToken('token')) expect(globalThis.fetch).toBeCalledWith( `${globalThis.RWJS_API_URL}/auth`, expect.objectContaining({ credentials: 'include', }) ) }) it('allows you to configure the api side url', async () => { const auth = getDbAuth({ dbAuthUrl: '/.redwood/functions/dbauth' }).current await act(async () => await auth.forgotPassword('username')) expect(fetchMock).toBeCalledWith( '/.redwood/functions/dbauth', expect.objectContaining({ credentials: 'same-origin', }) ) }) it('is not authenticated before logging in', async () => { const auth = getDbAuth().current await act(async () => { expect(auth.isAuthenticated).toBeFalsy() }) }) it('is authenticated after logging in', async () => { const authRef = getDbAuth() await act(async () => { authRef.current.logIn({ username: 'auth-test', password: 'ThereIsNoSpoon', }) }) expect(authRef.current.isAuthenticated).toBeTruthy() }) it('is not authenticated after logging out', async () => { const authRef = getDbAuth() await act(async () => { authRef.current.logIn({ username: 'auth-test', password: 'ThereIsNoSpoon', }) }) expect(authRef.current.isAuthenticated).toBeTruthy() await act(async () => { authRef.current.logOut() }) expect(authRef.current.isAuthenticated).toBeFalsy() }) it('does not affect logged in/out status when using forgotPassword', async () => { const authRef = getDbAuth() await act(async () => { authRef.current.logIn({ username: 'auth-test', password: 'ThereIsNoSpoon', }) }) expect(authRef.current.isAuthenticated).toBeTruthy() await act(async () => { authRef.current.forgotPassword('auth-test') }) expect(authRef.current.isAuthenticated).toBeTruthy() await act(async () => { authRef.current.logOut() }) expect(authRef.current.isAuthenticated).toBeFalsy() await act(async () => { authRef.current.forgotPassword('auth-test') }) expect(authRef.current.isAuthenticated).toBeFalsy() }) it('has role "user"', async () => { const authRef = getDbAuth() expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn({ username: 'auth-test', password: 'ThereIsNoSpoon', }) }) expect(authRef.current.hasRole('user')).toBeTruthy() }) it('can specify custom hasRole function', async () => { function useHasRole(currentUser: CurrentUser | null) { return (rolesToCheck: string | string[]) => { if (!currentUser || typeof rolesToCheck !== 'string') { return false } if (rolesToCheck === 'user') { // Everyone has role "user" return true } // For the admin role we check their email address if ( rolesToCheck === 'admin' && currentUser.email === '[email protected]' ) { return true } return false } } const authRef = getDbAuth({ useHasRole }) expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn({ username: '[email protected]', password: 'ThereIsNoSpoon', }) }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { authRef.current.logIn({ username: '[email protected]', password: 'ThereIsNoSpoon', }) }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom getCurrentUser function', async () => { async function useCurrentUser() { return { ...loggedInUser, roles: ['custom-current-user'], } } const authRef = getDbAuth({ useCurrentUser }) // Need to be logged in, otherwise getCurrentUser won't be invoked await act(async () => { authRef.current.logIn({ username: '[email protected]', password: 'ThereIsNoSpoon', }) }) await act(async () => { expect(authRef.current.hasRole('user')).toBeFalsy() expect(authRef.current.hasRole('custom-current-user')).toBeTruthy() }) }) })
4,288
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/dbAuth/web/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/dbAuth/web/src/__tests__/webAuthn.test.ts
import WebAuthnClient from '../webAuthn' globalThis.RWJS_API_URL = '/.redwood/functions' jest.mock('@whatwg-node/fetch', () => { return }) const mockOpen = jest.fn() const mockSend = jest.fn() const xhrMock: Partial<XMLHttpRequest> = { open: mockOpen, send: mockSend, setRequestHeader: jest.fn(), readyState: 4, status: 200, responseText: '{}', } jest .spyOn(global, 'XMLHttpRequest') .mockImplementation(() => xhrMock as XMLHttpRequest) function clearCookies() { document.cookie.split(';').forEach(function (c) { document.cookie = c .replace(/^ +/, '') .replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/') }) } beforeEach(() => { mockOpen.mockClear() mockSend.mockClear() clearCookies() }) describe('webAuthn', () => { it('can be constructed', () => { const webAuthnClient = new WebAuthnClient() expect(webAuthnClient).not.toBeNull() expect(webAuthnClient).not.toBe(undefined) }) it('uses the webAuthn cookie to check if webAuthn is enabled', () => { const webAuthnClient = new WebAuthnClient() clearCookies() expect(webAuthnClient.isEnabled()).toBeFalsy() document.cookie = 'someCookie=foobar' document.cookie = 'webAuthn=auth-id' document.cookie = 'SOME_OTHER_COOKIE=cannikin' expect(webAuthnClient.isEnabled()).toBeTruthy() clearCookies() document.cookie = 'someCookie=foobar' document.cookie = 'SOME_OTHER_COOKIE=cannikin' expect(webAuthnClient.isEnabled()).toBeFalsy() clearCookies() document.cookie = 'someCookie=foobar' document.cookie = 'webAuthn=auth-id' expect(webAuthnClient.isEnabled()).toBeTruthy() clearCookies() document.cookie = 'fakewebAuthn=fake-id' expect(webAuthnClient.isEnabled()).toBeFalsy() clearCookies() document.cookie = 'webAuthn=auth-id' document.cookie = 'SOME_OTHER_COOKIE=cannikin' expect(webAuthnClient.isEnabled()).toBeTruthy() }) it('uses default rwjs api url when calling authenticate()', async () => { const webAuthnClient = new WebAuthnClient() await webAuthnClient.authenticate() expect(mockOpen).toBeCalledWith( 'GET', `${globalThis.RWJS_API_URL}/auth?method=webAuthnAuthOptions`, false ) expect(mockOpen).toBeCalledWith( 'POST', `${globalThis.RWJS_API_URL}/auth`, false ) expect(mockSend).toBeCalledWith( expect.stringMatching(/"method":"webAuthnAuthenticate"/) ) expect(mockOpen).toHaveBeenCalledTimes(2) }) it('can be configured with a custom api auth url for authenticate()', async () => { const webAuthnClient = new WebAuthnClient() webAuthnClient.setAuthApiUrl('/.redwood/functions/webauthn') await webAuthnClient.authenticate() expect(mockOpen).toBeCalledWith( 'GET', '/.redwood/functions/webauthn?method=webAuthnAuthOptions', false ) expect(mockOpen).toBeCalledWith( 'POST', '/.redwood/functions/webauthn', false ) expect(mockSend).toBeCalledWith( expect.stringMatching(/"method":"webAuthnAuthenticate"/) ) expect(mockOpen).toHaveBeenCalledTimes(2) }) it('uses default rwjs api url when calling register()', async () => { const webAuthnClient = new WebAuthnClient() await webAuthnClient.register() expect(mockOpen).toBeCalledWith( 'GET', `${globalThis.RWJS_API_URL}/auth?method=webAuthnRegOptions`, false ) expect(mockOpen).toBeCalledWith( 'POST', `${globalThis.RWJS_API_URL}/auth`, false ) expect(mockSend).toBeCalledWith( expect.stringMatching(/"method":"webAuthnRegister"/) ) expect(mockOpen).toHaveBeenCalledTimes(2) }) it('can be configured with a custom api auth url for register()', async () => { const webAuthnClient = new WebAuthnClient() webAuthnClient.setAuthApiUrl('/.redwood/functions/webauthn') await webAuthnClient.register() expect(mockOpen).toBeCalledWith( 'GET', '/.redwood/functions/webauthn?method=webAuthnRegOptions', false ) expect(mockOpen).toBeCalledWith( 'POST', '/.redwood/functions/webauthn', false ) expect(mockSend).toBeCalledWith( expect.stringMatching(/"method":"webAuthnRegister"/) ) expect(mockOpen).toHaveBeenCalledTimes(2) }) })
4,298
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/firebase/api/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/firebase/api/src/__tests__/firebase.test.ts
import type { APIGatewayProxyEvent, Context as LambdaContext } from 'aws-lambda' import admin from 'firebase-admin' import { authDecoder } from '../decoder' const verifyIdToken = jest.fn() jest.spyOn(admin, 'auth').mockImplementation((() => { return { verifyIdToken, } }) as any) const req = { event: {} as APIGatewayProxyEvent, context: {} as LambdaContext, } test('returns null for unsupported type', async () => { const decoded = await authDecoder('token', 'netlify', req) expect(decoded).toBe(null) }) test('calls verifyIdToken', async () => { authDecoder('token', 'firebase', req) expect(verifyIdToken).toHaveBeenCalledWith('token') })
4,307
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/firebase/setup/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/firebase/setup/src/__tests__/setup.test.ts
import { command, description, builder, handler } from '../setup' // mock Telemetry for CLI commands so they don't try to spawn a process jest.mock('@redwoodjs/telemetry', () => { return { errorTelemetry: () => jest.fn(), timedTelemetry: () => jest.fn(), } }) test('standard exports', () => { expect(command).toEqual('firebase') expect(description).toMatch(/Firebase/) expect(typeof builder).toEqual('function') expect(typeof handler).toEqual('function') })
4,318
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/firebase/web/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/firebase/web/src/__tests__/firebase.test.tsx
import { renderHook, act } from '@testing-library/react' import type FirebaseAuthNamespace from 'firebase/auth' import type { User, OAuthProvider, Auth } from 'firebase/auth' import { OperationType } from 'firebase/auth' import type { CurrentUser } from '@redwoodjs/auth' import type { FirebaseClient } from '../firebase' import { createAuth } from '../firebase' const user: User = { uid: 'unique_user_id', displayName: 'John', email: '[email protected]', emailVerified: true, isAnonymous: false, metadata: {}, providerData: [], refreshToken: '', tenantId: null, delete: async () => {}, reload: async () => {}, toJSON: () => ({}), phoneNumber: '', photoURL: '', providerId: '', getIdToken: async () => 'token', getIdTokenResult: async () => { return { claims: { roles: ['user'], }, authTime: new Date().toUTCString(), expirationTime: new Date(Date.now() + 1000 * 3600).toUTCString(), issuedAtTime: new Date().toUTCString(), signInProvider: '', signInSecondFactor: null, token: 'token', } }, } const adminUser: User = { uid: 'unique_user_id_admin', displayName: 'Mr Smith', email: '[email protected]', emailVerified: true, isAnonymous: false, metadata: {}, providerData: [], refreshToken: '', tenantId: null, delete: async () => {}, reload: async () => {}, toJSON: () => ({}), phoneNumber: '', photoURL: '', providerId: '', getIdToken: async () => 'token', getIdTokenResult: async () => { return { claims: { roles: ['user', 'admin'], }, authTime: new Date().toUTCString(), expirationTime: new Date(Date.now() + 1000 * 3600).toUTCString(), issuedAtTime: new Date().toUTCString(), signInProvider: '', signInSecondFactor: null, token: 'token', } }, } let loggedInUser: User | undefined const firebaseAuth: Partial<typeof FirebaseAuthNamespace> = { getAuth: () => { const auth: Partial<Auth> = { onAuthStateChanged: () => { return () => {} }, signOut: async () => { loggedInUser = undefined }, get currentUser() { return loggedInUser }, } return auth as Auth }, OAuthProvider: function () {} as unknown as typeof OAuthProvider, isSignInWithEmailLink: () => { return false }, signInWithEmailAndPassword: async ( _auth: Auth, email: string, _password: string ) => { if (email.startsWith('admin')) { loggedInUser = adminUser } else { loggedInUser = user } return { user: loggedInUser, providerId: '', operationType: OperationType.SIGN_IN, } }, } const firebaseMockClient: FirebaseClient = { firebaseAuth: firebaseAuth as typeof FirebaseAuthNamespace, } const fetchMock = jest.fn() fetchMock.mockImplementation(async (_url, options) => { const body = options?.body ? JSON.parse(options.body) : {} if ( body.query === 'query __REDWOOD__AUTH_GET_CURRENT_USER { redwood { currentUser } }' ) { return { ok: true, text: () => '', json: () => ({ data: { redwood: { currentUser: loggedInUser } } }), } } return { ok: true, text: () => '', json: () => ({}) } }) beforeAll(() => { globalThis.fetch = fetchMock }) beforeEach(() => { fetchMock.mockClear() loggedInUser = undefined }) function getFirebaseAuth(customProviderHooks?: { useCurrentUser?: () => Promise<CurrentUser> useHasRole?: ( currentUser: CurrentUser | null ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( firebaseMockClient as FirebaseClient, customProviderHooks ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, }) return result } describe('firebaseAuth', () => { it('is not authenticated before logging in', async () => { const authRef = getFirebaseAuth() await act(async () => { expect(authRef.current.isAuthenticated).toBeFalsy() }) }) it('is authenticated after logging in', async () => { const authRef = getFirebaseAuth() await act(async () => { authRef.current.logIn({ email: '[email protected]', password: 'open-sesame', }) }) expect(authRef.current.isAuthenticated).toBeTruthy() }) it('is not authenticated after logging out', async () => { const authRef = getFirebaseAuth() await act(async () => { authRef.current.logIn({ email: '[email protected]', password: 'open-sesame', }) }) expect(authRef.current.isAuthenticated).toBeTruthy() await act(async () => { authRef.current.logOut() }) expect(authRef.current.isAuthenticated).toBeFalsy() }) // firebase doesn't support roles using RW's default implementation right now it.skip('has role "user"', async () => { const authRef = getFirebaseAuth() expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn({ email: '[email protected]', password: 'open-sesame', }) }) expect(authRef.current.hasRole('user')).toBeTruthy() }) // firebase doesn't support roles using RW's default implementation right now it.skip('has role "admin"', async () => { const authRef = getFirebaseAuth() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { authRef.current.logIn({ email: '[email protected]', password: 'open-sesame', }) }) expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom hasRole function', async () => { function useHasRole(currentUser: CurrentUser | null) { return (rolesToCheck: string | string[]) => { if (!currentUser || typeof rolesToCheck !== 'string') { return false } if (rolesToCheck === 'user') { // Everyone has role "user" return true } // For the admin role we check their email address if ( rolesToCheck === 'admin' && currentUser.email === '[email protected]' ) { return true } return false } } const authRef = getFirebaseAuth({ useHasRole }) expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn({ email: '[email protected]', password: 'open-sesame', }) }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { authRef.current.logIn({ email: '[email protected]', password: 'open-sesame', }) }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom getCurrentUser function', async () => { async function useCurrentUser() { const user = { ...loggedInUser, // Because we're writing our own custom getCurrentUser function we // can set roles where RW looks for them by default roles: ['custom-current-user'], } user.getIdTokenResult = async () => { return { claims: { roles: ['custom-current-user'], }, authTime: new Date().toUTCString(), expirationTime: new Date(Date.now() + 1000 * 3600).toUTCString(), issuedAtTime: new Date().toUTCString(), signInProvider: '', signInSecondFactor: null, token: 'token', } } return user } const authRef = getFirebaseAuth({ useCurrentUser }) // Need to be logged in, otherwise getCurrentUser won't be invoked await act(async () => { authRef.current.logIn({ email: '[email protected]', password: 'open-sesame', }) }) await act(async () => { expect(authRef.current.hasRole('user')).toBeFalsy() expect(authRef.current.hasRole('custom-current-user')).toBeTruthy() }) }) })
4,326
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/netlify/api/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/netlify/api/src/__tests__/netlify.test.ts
import type { APIGatewayProxyEvent, Context as LambdaContext } from 'aws-lambda' import jwt from 'jsonwebtoken' import { authDecoder } from '../decoder' jest.mock('jsonwebtoken', () => { const jsonwebtoken = jest.requireActual('jsonwebtoken') return { ...jsonwebtoken, verify: jest.fn(), decode: jest.fn((token: string) => { const exp = token === 'expired-token' ? Math.floor(Date.now() / 1000) - 3600 : Math.floor(Date.now() / 1000) + 3600 return { exp, sub: 'abc123' } }), } }) const req = { event: {} as APIGatewayProxyEvent, context: {} as LambdaContext, } let consoleError beforeAll(() => { consoleError = console.error console.error = () => {} }) afterAll(() => { console.error = consoleError }) test('returns null for unsupported type', async () => { const decoded = await authDecoder('token', 'clerk', req) expect(decoded).toBe(null) }) test('in production it uses req data', async () => { const NODE_ENV = process.env.NODE_ENV process.env.NODE_ENV = 'production' const decoded = await authDecoder('token', 'netlify', { ...req.event, context: { clientContext: { user: { sub: 'abc123' } } }, } as any) expect(jwt.decode).not.toBeCalled() expect(jwt.verify).not.toBeCalled() expect(decoded?.sub === 'abc123') process.env.NODE_ENV = NODE_ENV }) test('in dev and test it uses jwt.decode', async () => { const decoded = await authDecoder('token', 'netlify', { ...req.event, context: { clientContext: { user: { sub: 'abc123' } } }, } as any) expect(jwt.decode).toBeCalled() expect(jwt.verify).not.toBeCalled() expect(decoded?.sub === 'abc123') }) test('throws on expired token', async () => { expect( authDecoder('expired-token', 'netlify', { ...req.event, context: { clientContext: { user: { sub: 'abc123' } } }, } as any) ).rejects.toThrow('jwt expired') })
4,335
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/netlify/setup/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/netlify/setup/src/__tests__/setup.test.ts
import { command, description, builder, handler } from '../setup' // mock Telemetry for CLI commands so they don't try to spawn a process jest.mock('@redwoodjs/telemetry', () => { return { errorTelemetry: () => jest.fn(), timedTelemetry: () => jest.fn(), } }) test('standard exports', () => { expect(command).toEqual('netlify') expect(description).toMatch(/Netlify/) expect(typeof builder).toEqual('function') expect(typeof handler).toEqual('function') })
4,345
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/netlify/web/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/netlify/web/src/__tests__/netlify.test.tsx
import { renderHook, act } from '@testing-library/react' import type * as NetlifyIdentityNS from 'netlify-identity-widget' import type { CurrentUser } from '@redwoodjs/auth' import { createAuth } from '../netlify' type NetlifyIdentity = typeof NetlifyIdentityNS type User = NetlifyIdentityNS.User const user: Partial<User> = { id: 'unique_user_id', user_metadata: { full_name: 'John Doe', }, email: '[email protected]', app_metadata: { provider: 'netlify', roles: ['user'], }, } const adminUser: Partial<User> = { id: 'unique_user_id_admin', user_metadata: { full_name: 'Mr Smith', }, email: '[email protected]', app_metadata: { provider: 'netlify', roles: ['user', 'admin'], }, } let loggedInUser: User | undefined function on(event: 'init', cb: (user: User | null) => void): void function on(event: 'login', cb: (user: User) => void): void function on(event: 'logout' | 'open' | 'close', cb: () => void): void function on(event: 'error', cb: (err: Error) => void): void function on(_event: unknown, cb: (arg?: any) => void) { cb() } const netlifyIdentityMockClient: Partial<NetlifyIdentity> = { open: () => { loggedInUser ||= user as User return loggedInUser }, on, close: () => {}, logout: async () => { loggedInUser = undefined }, refresh: async () => 'token', currentUser: () => loggedInUser || null, } const fetchMock = jest.fn() fetchMock.mockImplementation(async (_url, options) => { const body = options?.body ? JSON.parse(options.body) : {} if ( body.query === 'query __REDWOOD__AUTH_GET_CURRENT_USER { redwood { currentUser } }' ) { return { ok: true, text: () => '', json: () => ({ data: { redwood: { currentUser: { ...loggedInUser, roles: loggedInUser?.app_metadata?.roles, }, }, }, }), } } return { ok: true, text: () => '', json: () => ({}) } }) beforeAll(() => { global.fetch = fetchMock }) beforeEach(() => { fetchMock.mockClear() loggedInUser = undefined }) function getNetlifyAuth(customProviderHooks?: { useCurrentUser?: () => Promise<CurrentUser> useHasRole?: ( currentUser: CurrentUser | null ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( netlifyIdentityMockClient as NetlifyIdentity, customProviderHooks ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, }) return result } describe('Netlify', () => { it('is not authenticated before logging in', async () => { const auth = getNetlifyAuth().current await act(async () => { expect(auth.isAuthenticated).toBeFalsy() }) }) it('is authenticated after logging in', async () => { const authRef = getNetlifyAuth() await act(async () => { authRef.current.logIn() }) expect(authRef.current.isAuthenticated).toBeTruthy() }) it('is not authenticated after logging out', async () => { const authRef = getNetlifyAuth() await act(async () => { authRef.current.logIn() }) expect(authRef.current.isAuthenticated).toBeTruthy() await act(async () => { await authRef.current.logOut() }) expect(authRef.current.isAuthenticated).toBeFalsy() }) it('has role "user"', async () => { const authRef = getNetlifyAuth() expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() }) it('has role "admin"', async () => { const authRef = getNetlifyAuth() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { loggedInUser = adminUser as User authRef.current.logIn() }) expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom hasRole function', async () => { function useHasRole(currentUser: CurrentUser | null) { return (rolesToCheck: string | string[]) => { if (!currentUser || typeof rolesToCheck !== 'string') { return false } if (rolesToCheck === 'user') { // Everyone has role "user" return true } // For the admin role we check their email address if ( rolesToCheck === 'admin' && currentUser.email === '[email protected]' ) { return true } return false } } const authRef = getNetlifyAuth({ useHasRole }) expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { loggedInUser = adminUser as User authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom getCurrentUser function', async () => { async function useCurrentUser() { return { ...loggedInUser, roles: ['custom-current-user'], } } const authRef = getNetlifyAuth({ useCurrentUser }) // Need to be logged in, otherwise getCurrentUser won't be invoked await act(async () => { authRef.current.logIn() }) await act(async () => { expect(authRef.current.hasRole('user')).toBeFalsy() expect(authRef.current.hasRole('custom-current-user')).toBeTruthy() }) }) })
4,353
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/supabase/api/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/supabase/api/src/__tests__/supabase.test.ts
import type { APIGatewayProxyEvent, Context as LambdaContext } from 'aws-lambda' import jwt from 'jsonwebtoken' import { authDecoder } from '../decoder' jest.mock('jsonwebtoken', () => { return { verify: jest.fn(() => { return { sub: 'abc123', } }), decode: jest.fn(), } }) const req = { event: {} as APIGatewayProxyEvent, context: {} as LambdaContext, } let consoleError beforeAll(() => { consoleError = console.error console.error = () => {} }) afterAll(() => { console.error = consoleError }) test('returns null for unsupported type', async () => { const decoded = await authDecoder('token', 'clerk', req) expect(decoded).toBe(null) }) test('throws if SUPABASE_JWT_SECRET env var is not set', async () => { delete process.env.SUPABASE_JWT_SECRET await expect(authDecoder('token', 'supabase', req)).rejects.toThrow( 'SUPABASE_JWT_SECRET env var is not set' ) }) test('verifies the token with secret from env', () => { process.env.SUPABASE_JWT_SECRET = 'jwt-secret' authDecoder('token', 'supabase', req) expect(jwt.verify).toHaveBeenCalledWith('token', 'jwt-secret') }) test('returns verified data', async () => { process.env.SUPABASE_JWT_SECRET = 'jwt-secret' const decoded = await authDecoder('token', 'supabase', req) expect(decoded?.sub).toEqual('abc123') })
4,371
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/supabase/web/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/supabase/web/src/__tests__/supabase.test.tsx
import type { SupabaseClient, User, AuthResponse, OAuthResponse, SSOResponse, SignInWithOAuthCredentials, SignInWithIdTokenCredentials, SignInWithPasswordlessCredentials, SignInWithSSO, SignInWithPasswordCredentials, SignUpWithPasswordCredentials, Session, } from '@supabase/supabase-js' import { AuthError } from '@supabase/supabase-js' import { renderHook, act } from '@testing-library/react' import type { CurrentUser } from '@redwoodjs/auth' import { createAuth } from '../supabase' const user: User = { id: 'unique_user_id', aud: 'authenticated', user_metadata: { full_name: 'John Doe', }, email: '[email protected]', app_metadata: { provider: 'supabase', roles: ['user'], }, created_at: new Date().toUTCString(), } const adminUser: User = { id: 'unique_user_id_admin', aud: 'authenticated', user_metadata: { full_name: 'Mr Smith', }, email: '[email protected]', app_metadata: { provider: 'supabase', roles: ['user', 'admin'], }, created_at: new Date().toUTCString(), } const oAuthUser: User = { id: 'unique_user_id', aud: 'authenticated', user_metadata: { full_name: 'Octo Cat', }, email: '[email protected]', app_metadata: { provider: 'github', roles: ['user'], }, created_at: new Date().toUTCString(), } let loggedInUser: User | undefined const mockSupabaseAuthClient: Partial<SupabaseClient['auth']> = { signInWithPassword: async ( credentials: SignInWithPasswordCredentials ): Promise<AuthResponse> => { const { email } = credentials as { email: string } loggedInUser = email === '[email protected]' ? adminUser : user loggedInUser.email = email return { data: { user: loggedInUser, session: null, }, error: null, } }, signInWithOAuth: async ( credentials: SignInWithOAuthCredentials ): Promise<OAuthResponse> => { loggedInUser = oAuthUser return { data: { provider: credentials.provider, url: `https://${credentials.provider}.com`, }, error: null, } }, signInWithOtp: async ( credentials: SignInWithPasswordlessCredentials ): Promise<AuthResponse> => { loggedInUser = user loggedInUser.email = credentials['email'] return { data: { user: loggedInUser, session: null, }, error: null, } }, signInWithIdToken: async ( credentials: SignInWithIdTokenCredentials ): Promise<AuthResponse> => { loggedInUser = user const session = { access_token: `token ${credentials.token}`, refresh_token: 'refresh_token_1234567890', token_type: `Bearer ${credentials.provider}`, expires_in: 999, } loggedInUser.app_metadata = session return { data: { user: null, session: { user: loggedInUser, ...session, }, }, error: null, } }, signInWithSSO: async (credentials: SignInWithSSO): Promise<SSOResponse> => { loggedInUser = user const url = `https://${credentials['domain']}.${credentials['providerId']}.com` loggedInUser.app_metadata = { url, domain: credentials['domain'], providerId: credentials['providerId'], } return { data: { url, }, error: null, } }, signOut: async () => { loggedInUser = undefined return { error: null } }, signUp: async ( credentials: SignUpWithPasswordCredentials ): Promise<AuthResponse> => { const { email } = credentials as { email: string } loggedInUser = email === '[email protected]' ? adminUser : user loggedInUser.email = email if (credentials.options) { loggedInUser.user_metadata = credentials.options } console.log('signUp', loggedInUser) return { data: { user: loggedInUser, session: null, }, error: null, } }, getSession: async (): Promise< | { data: { session: Session } error: null } | { data: { session: null } error: AuthError } | { data: { session: null } error: null } > => { if (loggedInUser) { return { data: { session: { access_token: 'token', refresh_token: 'token', expires_in: 999, token_type: 'Bearer', user: loggedInUser, }, }, error: null, } } return { data: { session: null }, error: new AuthError('Not logged in'), } }, refreshSession: async (currentSession?: { refresh_token: string }): Promise<AuthResponse> => { if (loggedInUser) { return { data: { user: loggedInUser, session: { access_token: 'jwt_1234567890', refresh_token: `refresh_token_1234567890_${currentSession?.refresh_token}`, expires_in: 999, token_type: 'Bearer', user: loggedInUser, }, }, error: null, } } return { data: { user: null, session: null }, error: new AuthError('Not logged in'), } }, } const supabaseMockClient: Partial<SupabaseClient> = { auth: mockSupabaseAuthClient as SupabaseClient['auth'], } const fetchMock = jest.fn() fetchMock.mockImplementation(async (_url, options) => { const body = options?.body ? JSON.parse(options.body) : {} if ( body.query === 'query __REDWOOD__AUTH_GET_CURRENT_USER { redwood { currentUser } }' ) { return { ok: true, text: () => '', json: () => ({ data: { redwood: { currentUser: { ...loggedInUser, roles: loggedInUser?.app_metadata?.roles, }, }, }, }), } } return { ok: true, text: () => '', json: () => ({}) } }) beforeAll(() => { globalThis.fetch = fetchMock }) beforeEach(() => { fetchMock.mockClear() loggedInUser = undefined }) function getSupabaseAuth(customProviderHooks?: { useCurrentUser?: () => Promise<CurrentUser> useHasRole?: ( currentUser: CurrentUser | null ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( supabaseMockClient as SupabaseClient, customProviderHooks ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, }) return result } describe('Supabase Authentication', () => { it('is not authenticated before logging in', async () => { const authRef = getSupabaseAuth() await act(async () => { expect(authRef.current.isAuthenticated).toBeFalsy() }) }) describe('Password Authentication', () => { describe('Sign up', () => { it('is authenticated after signing up with username and password', async () => { const authRef = getSupabaseAuth() await act(async () => { authRef.current.signUp({ email: '[email protected]', password: 'ThereIsNoSpoon', }) }) const currentUser = authRef.current.currentUser expect(authRef.current.isAuthenticated).toBeTruthy() expect(currentUser?.email).toEqual('[email protected]') }) it('is authenticated after signing up with username and password and additional metadata', async () => { const authRef = getSupabaseAuth() await act(async () => { authRef.current.signUp({ email: '[email protected]', password: 'ThereIsNoSpoon', options: { data: { first_name: 'Jane', age: 27, }, }, }) }) const currentUser = authRef.current.currentUser const userMetadata = authRef.current.userMetadata expect(authRef.current.isAuthenticated).toBeTruthy() expect(currentUser?.email).toEqual('[email protected]') expect(userMetadata?.data?.first_name).toEqual('Jane') expect(userMetadata?.data?.age).toEqual(27) }) it('is authenticated after signing up with username and password and a redirect URL', async () => { const authRef = getSupabaseAuth() await act(async () => { authRef.current.signUp({ email: '[email protected]', password: 'example-password', options: { emailRedirectTo: 'https://example.com/welcome', }, }) }) const currentUser = authRef.current.currentUser expect(authRef.current.isAuthenticated).toBeTruthy() expect(currentUser?.email).toEqual('[email protected]') }) }) it('is authenticated after logging in', async () => { const authRef = getSupabaseAuth() await act(async () => { authRef.current.logIn({ authMethod: 'password', email: '[email protected]', password: 'ThereIsNoSpoon', }) }) const currentUser = authRef.current.currentUser expect(authRef.current.isAuthenticated).toBeTruthy() expect(currentUser?.email).toEqual('[email protected]') }) it('is not authenticated after logging out', async () => { const authRef = getSupabaseAuth() await act(async () => { authRef.current.logIn({ authMethod: 'password', email: '[email protected]', password: 'ThereIsNoSpoon', }) }) expect(authRef.current.isAuthenticated).toBeTruthy() await act(async () => { await authRef.current.logOut() }) expect(authRef.current.isAuthenticated).toBeFalsy() }) it('has role "user"', async () => { const authRef = getSupabaseAuth() expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn({ authMethod: 'password', email: '[email protected]', password: 'ThereIsNoSpoon', }) }) expect(authRef.current.hasRole('user')).toBeTruthy() }) it('has role "admin"', async () => { const authRef = getSupabaseAuth() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { loggedInUser = adminUser authRef.current.logIn({ authMethod: 'password', email: '[email protected]', password: 'RedPill', }) }) expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom hasRole function', async () => { function useHasRole(currentUser: CurrentUser | null) { return (rolesToCheck: string | string[]) => { if (!currentUser || typeof rolesToCheck !== 'string') { return false } if (rolesToCheck === 'user') { // Everyone has role "user" return true } // For the admin role we check their email address if ( rolesToCheck === 'admin' && currentUser.email === '[email protected]' ) { return true } return false } } const authRef = getSupabaseAuth({ useHasRole }) expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn({ authMethod: 'password', email: '[email protected]', password: 'ThereIsNoSpoon', }) }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { loggedInUser = adminUser authRef.current.logIn({ authMethod: 'password', email: '[email protected]', password: 'RedPill', }) }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom getCurrentUser function', async () => { async function useCurrentUser() { return { ...loggedInUser, roles: ['custom-current-user'], } } const authRef = getSupabaseAuth({ useCurrentUser }) // Need to be logged in, otherwise getCurrentUser won't be invoked await act(async () => { authRef.current.logIn({ authMethod: 'password', email: '[email protected]', password: 'ThereIsNoSpoon', }) }) await act(async () => { expect(authRef.current.hasRole('user')).toBeFalsy() expect(authRef.current.hasRole('custom-current-user')).toBeTruthy() }) }) }) describe('OAuth Authentication', () => { it('is authenticated after logging in with an OAuth provider', async () => { const authRef = getSupabaseAuth() await act(async () => { authRef.current.logIn({ authMethod: 'oauth', provider: 'github', }) }) // In a real RW app the type for `currentUser` is generated from the // return type of getCurrentUser in api/lib/auth. Here we have to // cast it to the correct type const currentUser = authRef.current.currentUser as User | null expect(authRef.current.isAuthenticated).toBeTruthy() expect(currentUser?.app_metadata?.provider).toEqual('github') }) }) describe('Passwordless/OTP Authentication', () => { it('is authenticated after logging just an email', async () => { const authRef = getSupabaseAuth() await act(async () => { authRef.current.logIn({ authMethod: 'otp', email: '[email protected]', }) }) // In a real RW app the type for `currentUser` is generated from the // return type of getCurrentUser in api/lib/auth. Here we have to // cast it to the correct type const currentUser = authRef.current.currentUser as User | null expect(authRef.current.isAuthenticated).toBeTruthy() expect(currentUser?.email).toEqual('[email protected]') }) }) describe('IDToken Authentication', () => { it('is authenticated after logging with Apple IDToken', async () => { const authRef = getSupabaseAuth() await act(async () => { authRef.current.logIn({ authMethod: 'id_token', provider: 'apple', token: 'cortland-apple-id-token', }) }) // In a real RW app the type for `currentUser` is generated from the // return type of getCurrentUser in api/lib/auth. Here we have to // cast it to the correct type const currentUser = authRef.current.currentUser as User | null const appMetadata = currentUser?.app_metadata expect(authRef.current.isAuthenticated).toBeTruthy() expect(appMetadata?.access_token).toEqual('token cortland-apple-id-token') expect(appMetadata?.token_type).toEqual('Bearer apple') }) }) describe('SSO Authentication', () => { it('is authenticated after logging with SSO', async () => { const authRef = getSupabaseAuth() await act(async () => { authRef.current.logIn({ authMethod: 'sso', providerId: 'sso-provider-identity-uuid', domain: 'example.com', }) }) // In a real RW app the type for `currentUser` is generated from the // return type of getCurrentUser in api/lib/auth. Here we have to // cast it to the correct type const currentUser = authRef.current.currentUser as User | null const appMetadata = currentUser?.app_metadata expect(authRef.current.isAuthenticated).toBeTruthy() expect(appMetadata?.domain).toEqual('example.com') expect(appMetadata?.providerId).toEqual('sso-provider-identity-uuid') }) }) })
4,379
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/supertokens/api/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/supertokens/api/src/__tests__/supertokens.test.ts
import type { APIGatewayProxyEvent, Context as LambdaContext } from 'aws-lambda' import jwt from 'jsonwebtoken' import { authDecoder } from '../decoder' jest.mock('jsonwebtoken', () => { return { verify: jest.fn(), decode: jest.fn(), } }) const req = { event: {} as APIGatewayProxyEvent, context: {} as LambdaContext, } let consoleError beforeAll(() => { consoleError = console.error console.error = () => {} }) afterAll(() => { console.error = consoleError }) test('returns null for unsupported type', async () => { const decoded = await authDecoder('token', 'clerk', req) expect(decoded).toBe(null) }) test('throws if SUPERTOKENS_JWKS_URL env var is not set', async () => { delete process.env.SUPERTOKENS_JWKS_URL await expect(authDecoder('token', 'supertokens', req)).rejects.toThrow( 'SUPERTOKENS_JWKS_URL env var is not set' ) }) test('uses verify', () => { process.env.SUPERTOKENS_JWKS_URL = 'jwks-url' authDecoder('token', 'supertokens', req) expect(jwt.verify).toHaveBeenCalled() })
4,389
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/supertokens/setup/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/supertokens/setup/src/__tests__/setup.test.ts
import { command, description, builder, handler } from '../setup' // mock Telemetry for CLI commands so they don't try to spawn a process jest.mock('@redwoodjs/telemetry', () => { return { errorTelemetry: () => jest.fn(), timedTelemetry: () => jest.fn(), } }) test('standard exports', () => { expect(command).toEqual('supertokens') expect(description).toMatch(/SuperTokens/) expect(typeof builder).toEqual('function') expect(typeof handler).toEqual('function') })
4,390
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/supertokens/setup/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/supertokens/setup/src/__tests__/setupHandler.test.ts
// mock Telemetry for CLI commands so they don't try to spawn a process jest.mock('@redwoodjs/telemetry', () => { return { errorTelemetry: () => jest.fn(), timedTelemetry: () => jest.fn(), } }) jest.mock('@redwoodjs/cli-helpers', () => { return { getPaths: () => { return { web: { src: '', app: '', routes: 'Routes.tsx', }, base: '', } }, standardAuthHandler: () => jest.fn(), } }) // This will load packages/auth-providers/supertokens/setup/__mocks__/fs.js jest.mock('fs') const mockFS = fs as unknown as Omit<jest.Mocked<typeof fs>, 'readdirSync'> & { __setMockFiles: (files: Record<string, string>) => void } import fs from 'fs' import { addRoutingLogic } from '../setupHandler' describe('addRoutingLogic', () => { it('modifies the Routes.{jsx,tsx} file', () => { mockFS.__setMockFiles({ 'Routes.tsx': "// In this file, all Page components from 'src/pages' are auto-imported.\n" + ` import { Router, Route } from '@redwoodjs/router' import { useAuth } from './auth' const Routes = () => { return ( <Router useAuth={useAuth}> <Route path="/login" page={LoginPage} name="login" /> <Route path="/signup" page={SignupPage} name="signup" /> <Route notfound page={NotFoundPage} /> </Router> ) } export default Routes `, }) addRoutingLogic.task() expect(mockFS.readFileSync('Routes.tsx')).toMatchInlineSnapshot(` "// In this file, all Page components from 'src/pages' are auto-imported. import { canHandleRoute, getRoutingComponent } from 'supertokens-auth-react/ui' import { Router, Route } from '@redwoodjs/router' import { useAuth, PreBuiltUI } from './auth' const Routes = () => { if (canHandleRoute(PreBuiltUI)) { return getRoutingComponent(PreBuiltUI) } return ( <Router useAuth={useAuth}> <Route path="/login" page={LoginPage} name="login" /> <Route path="/signup" page={SignupPage} name="signup" /> <Route notfound page={NotFoundPage} /> </Router> ) } export default Routes " `) }) it('handles a Routes.{jsx,tsx} file with a legacy setup', () => { mockFS.__setMockFiles({ 'Routes.tsx': "// In this file, all Page components from 'src/pages' are auto-imported.\n" + ` import SuperTokens from 'supertokens-auth-react' import { Router, Route } from '@redwoodjs/router' import { useAuth } from './auth' const Routes = () => { if (SuperTokens.canHandleRoute()) { return SuperTokens.getRoutingComponent() } return ( <Router useAuth={useAuth}> <Route path="/login" page={LoginPage} name="login" /> <Route path="/signup" page={SignupPage} name="signup" /> <Route notfound page={NotFoundPage} /> </Router> ) } export default Routes `, }) addRoutingLogic.task() expect(mockFS.readFileSync('Routes.tsx')).toMatchInlineSnapshot(` "// In this file, all Page components from 'src/pages' are auto-imported. import { canHandleRoute, getRoutingComponent } from 'supertokens-auth-react/ui' import { Router, Route } from '@redwoodjs/router' import { useAuth, PreBuiltUI } from './auth' const Routes = () => { if (canHandleRoute(PreBuiltUI)) { return getRoutingComponent(PreBuiltUI) } return ( <Router useAuth={useAuth}> <Route path="/login" page={LoginPage} name="login" /> <Route path="/signup" page={SignupPage} name="signup" /> <Route notfound page={NotFoundPage} /> </Router> ) } export default Routes " `) }) })
4,402
0
petrpan-code/redwoodjs/redwood/packages/auth-providers/supertokens/web/src
petrpan-code/redwoodjs/redwood/packages/auth-providers/supertokens/web/src/__tests__/supertokens.test.tsx
import { renderHook, act } from '@testing-library/react' import type { CurrentUser } from '@redwoodjs/auth' import type { SuperTokensUser, SessionRecipe, SuperTokensAuth, } from '../supertokens' import { createAuth } from '../supertokens' const user: SuperTokensUser = { userId: 'unique_user_id', accessTokenPayload: undefined, } const adminUser: SuperTokensUser = { userId: 'unique_user_id_admin', accessTokenPayload: undefined, } let loggedInUser: SuperTokensUser | undefined const superTokensSessionRecipe: SessionRecipe = { signOut: async () => { loggedInUser = undefined }, doesSessionExist: async () => true, getAccessTokenPayloadSecurely: async () => { return { _jwtPName: 'token', } }, getUserId: () => { return new Promise((resolve, reject) => { if (loggedInUser) { resolve(loggedInUser.userId) } else { reject('User not logged in') } }) }, } const superTokensMockClient: SuperTokensAuth = { sessionRecipe: superTokensSessionRecipe, redirectToAuth: async () => { loggedInUser ||= user }, } const fetchMock = jest.fn() fetchMock.mockImplementation(async (_url, options) => { const body = options?.body ? JSON.parse(options.body) : {} if ( body.query === 'query __REDWOOD__AUTH_GET_CURRENT_USER { redwood { currentUser } }' ) { return { ok: true, text: () => '', json: () => ({ data: { redwood: { currentUser: loggedInUser } } }), } } return { ok: true, text: () => '', json: () => ({}) } }) beforeAll(() => { globalThis.fetch = fetchMock }) beforeEach(() => { fetchMock.mockClear() loggedInUser = undefined }) function getSuperTokensAuth(customProviderHooks?: { useCurrentUser?: () => Promise<CurrentUser> useHasRole?: ( currentUser: CurrentUser | null ) => (rolesToCheck: string | string[]) => boolean }) { const { useAuth, AuthProvider } = createAuth( superTokensMockClient as SuperTokensAuth, customProviderHooks ) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, }) return result } describe('SuperTokens', () => { it('is not authenticated before logging in', async () => { const authRef = getSuperTokensAuth() await act(async () => { expect(authRef.current.isAuthenticated).toBeFalsy() }) }) it('is authenticated after logging in', async () => { const authRef = getSuperTokensAuth() await act(async () => { authRef.current.logIn() }) expect(authRef.current.isAuthenticated).toBeTruthy() }) it('is not authenticated after logging out', async () => { const authRef = getSuperTokensAuth() await act(async () => { authRef.current.logIn() }) expect(authRef.current.isAuthenticated).toBeTruthy() await act(async () => { await authRef.current.logOut() }) expect(authRef.current.isAuthenticated).toBeFalsy() }) // No support for roles using SuperTokens with Redwood's default hasRole // implementation right now it.skip('has role "user"', async () => { const authRef = getSuperTokensAuth() expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() }) // No support for roles using SuperTokens with Redwood's default hasRole // implementation right now it.skip('has role "admin"', async () => { const authRef = getSuperTokensAuth() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { loggedInUser = adminUser authRef.current.logIn() }) expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom hasRole function', async () => { function useHasRole(currentUser: CurrentUser | null) { return (rolesToCheck: string | string[]) => { if (!currentUser || typeof rolesToCheck !== 'string') { return false } if (rolesToCheck === 'user') { // Everyone has role "user" return true } // For the admin role we check their userId if ( rolesToCheck === 'admin' && currentUser.userId === 'unique_user_id_admin' ) { return true } return false } } const authRef = getSuperTokensAuth({ useHasRole }) expect(authRef.current.hasRole('user')).toBeFalsy() await act(async () => { authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeFalsy() await act(async () => { loggedInUser = adminUser authRef.current.logIn() }) expect(authRef.current.hasRole('user')).toBeTruthy() expect(authRef.current.hasRole('admin')).toBeTruthy() }) it('can specify custom getCurrentUser function', async () => { async function useCurrentUser() { return { ...loggedInUser, roles: ['custom-current-user'], } } const authRef = getSuperTokensAuth({ useCurrentUser }) // Need to be logged in, otherwise getCurrentUser won't be invoked await act(async () => { authRef.current.logIn() }) await act(async () => { expect(authRef.current.hasRole('user')).toBeFalsy() expect(authRef.current.hasRole('custom-current-user')).toBeTruthy() }) }) })
4,426
0
petrpan-code/redwoodjs/redwood/packages/auth/src
petrpan-code/redwoodjs/redwood/packages/auth/src/__tests__/AuthProvider.test.tsx
require('whatwg-fetch') import React, { useEffect, useState } from 'react' import { render, screen, fireEvent, waitFor, configure, } from '@testing-library/react' import { renderHook, act } from '@testing-library/react' import '@testing-library/jest-dom/extend-expect' import { graphql } from 'msw' import { setupServer } from 'msw/node' import type { CustomTestAuthClient } from './fixtures/customTestAuth' import { createCustomTestAuth } from './fixtures/customTestAuth' configure({ asyncUtilTimeout: 5_000, }) let CURRENT_USER_DATA: { name: string email: string roles?: string | string[] } = { name: 'Peter Pistorius', email: '[email protected]', } globalThis.RWJS_API_GRAPHQL_URL = '/.netlify/functions/graphql' const server = setupServer( graphql.query('__REDWOOD__AUTH_GET_CURRENT_USER', (_req, res, ctx) => { return res( ctx.data({ redwood: { currentUser: CURRENT_USER_DATA, }, }) ) }) ) const consoleError = console.error beforeAll(() => { server.listen() console.error = () => {} }) afterAll(() => { server.close() console.error = consoleError }) const customTestAuth: CustomTestAuthClient = { login: () => true, signup: () => {}, logout: () => {}, getToken: () => 'hunter2', getUserMetadata: jest.fn(() => null), forgotPassword: () => {}, resetPassword: () => true, validateResetToken: () => ({}), } async function getCustomTestAuth() { const { AuthProvider, useAuth } = createCustomTestAuth(customTestAuth) const { result } = renderHook(() => useAuth(), { wrapper: AuthProvider, }) return result.current } beforeEach(() => { server.resetHandlers() CURRENT_USER_DATA = { name: 'Peter Pistorius', email: '[email protected]', } customTestAuth.getUserMetadata = jest.fn(() => null) }) describe('Custom auth provider', () => { const { AuthProvider, useAuth } = createCustomTestAuth(customTestAuth) const AuthConsumer = () => { const { loading, isAuthenticated, logOut, logIn, getToken, userMetadata, currentUser, reauthenticate, hasError, hasRole, error, } = useAuth() const [authToken, setAuthToken] = useState<string | null>(null) useEffect(() => { const retrieveToken = async () => { const token = await getToken() setAuthToken(token) } retrieveToken() }, [getToken]) if (loading) { return <>Loading...</> } if (hasError) { return <>{error?.message}</> } return ( <> <button onClick={() => { isAuthenticated ? logOut() : logIn() }} > {isAuthenticated ? 'Log Out' : 'Log In'} </button> {isAuthenticated && ( <> <p>userMetadata: {JSON.stringify(userMetadata)}</p> <p>authToken: {authToken}</p> <p> currentUser:{' '} {(currentUser && JSON.stringify(currentUser)) || 'no current user data'} </p> <p>Has Admin: {hasRole('admin') ? 'yes' : 'no'}</p> <p>Has Super User: {hasRole('superuser') ? 'yes' : 'no'}</p> <p>Has Admin as Array: {hasRole(['admin']) ? 'yes' : 'no'}</p> <p>Has Editor: {hasRole(['editor', 'publisher']) ? 'yes' : 'no'}</p> <p> Has Editor or Author:{' '} {hasRole(['editor', 'author']) ? 'yes' : 'no'} </p> <button onClick={() => reauthenticate()}>Update auth data</button> </> )} </> ) } /** * A logged out user can login, view their personal account information and logout. */ test('Authentication flow (logged out -> login -> logged in -> logout) works as expected', async () => { const mockAuthClient = customTestAuth render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(mockAuthClient.getUserMetadata).toBeCalledTimes(1) // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(mockAuthClient.getUserMetadata).toBeCalledTimes(1) expect( screen.getByText( 'userMetadata: {"sub":"abcdefg|123456","username":"peterp"}' ) ).toBeInTheDocument() expect( screen.getByText( 'currentUser: {"name":"Peter Pistorius","email":"[email protected]"}' ) ).toBeInTheDocument() expect(screen.getByText('authToken: hunter2')).toBeInTheDocument() // Log out fireEvent.click(screen.getByText('Log Out')) await waitFor(() => screen.getByText('Log In')) }) test('Fetching the current user can be skipped', async () => { const mockAuthClient = customTestAuth render( <AuthProvider skipFetchCurrentUser> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(mockAuthClient.getUserMetadata).toBeCalledTimes(1) // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(mockAuthClient.getUserMetadata).toBeCalledTimes(1) expect(screen.getByText(/no current user data/)).toBeInTheDocument() // Log out fireEvent.click(screen.getByText('Log Out')) await waitFor(() => screen.getByText('Log In')) }) /** * This is especially helpful if you want to update the currentUser state. */ test('A user can be re-authenticated to update the "auth state"', async () => { const mockAuthClient = customTestAuth render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(mockAuthClient.getUserMetadata).toBeCalledTimes(1) // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(mockAuthClient.getUserMetadata).toBeCalledTimes(1) // The original current user data is fetched. expect( screen.getByText( 'currentUser: {"name":"Peter Pistorius","email":"[email protected]"}' ) ).toBeInTheDocument() CURRENT_USER_DATA = { ...CURRENT_USER_DATA, name: 'Rambo' } fireEvent.click(screen.getByText('Update auth data')) await waitFor(() => screen.getByText( 'currentUser: {"name":"Rambo","email":"[email protected]"}' ) ) }) test('When the current user cannot be fetched the user is not authenticated', async () => { server.use( graphql.query('__REDWOOD__AUTH_GET_CURRENT_USER', (_req, res, ctx) => { return res(ctx.status(404)) }) ) const mockAuthClient = customTestAuth mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() await waitFor(() => screen.getByText('Could not fetch current user: Not Found (404)') ) }) /** * Check assigned role access */ test('Authenticated user has assigned role access as expected', async () => { const mockAuthClient = customTestAuth CURRENT_USER_DATA = { name: 'Peter Pistorius', email: '[email protected]', roles: ['janitor'], } render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(screen.queryByText('Has Admin:')).not.toBeInTheDocument() expect(screen.queryByText('Has Super User:')).not.toBeInTheDocument() // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(screen.getByText('Has Admin: no')).toBeInTheDocument() expect(screen.getByText('Has Super User: no')).toBeInTheDocument() // Log out fireEvent.click(screen.getByText('Log Out')) await waitFor(() => screen.getByText('Log In')) }) /** * Check unassigned role access */ test('Authenticated user has not been assigned role access as expected', async () => { const mockAuthClient = customTestAuth CURRENT_USER_DATA = { name: 'Peter Pistorius', email: '[email protected]', roles: ['admin', 'superuser'], } render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(screen.queryByText('Has Admin:')).not.toBeInTheDocument() expect(screen.queryByText('Has Super User:')).not.toBeInTheDocument() // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(screen.getByText('Has Admin: yes')).toBeInTheDocument() expect(screen.getByText('Has Super User: yes')).toBeInTheDocument() // Log out fireEvent.click(screen.getByText('Log Out')) await waitFor(() => screen.getByText('Log In')) }) /** * Check some unassigned role access */ test('Authenticated user has not been assigned some role access but not others as expected', async () => { const mockAuthClient = customTestAuth CURRENT_USER_DATA = { name: 'Peter Pistorius', email: '[email protected]', roles: ['admin'], } render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(screen.queryByText('Has Admin:')).not.toBeInTheDocument() expect(screen.queryByText('Has Super User:')).not.toBeInTheDocument() // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(screen.getByText('Has Admin: yes')).toBeInTheDocument() expect(screen.getByText('Has Super User: no')).toBeInTheDocument() // Log out fireEvent.click(screen.getByText('Log Out')) await waitFor(() => screen.getByText('Log In')) }) /** * Check assigned role access when specified as single array element */ test('Authenticated user has assigned role access as expected', async () => { const mockAuthClient = customTestAuth CURRENT_USER_DATA = { name: 'Peter Pistorius', email: '[email protected]', roles: ['admin'], } render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(screen.queryByText('Has Admin:')).not.toBeInTheDocument() expect(screen.queryByText('Has Super User:')).not.toBeInTheDocument() // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(screen.getByText('Has Admin as Array: yes')).toBeInTheDocument() // Log out fireEvent.click(screen.getByText('Log Out')) await waitFor(() => screen.getByText('Log In')) }) /** * Check assigned role access when specified as array element */ test('Authenticated user has assigned role access as expected', async () => { const mockAuthClient = customTestAuth CURRENT_USER_DATA = { name: 'Peter Pistorius', email: '[email protected]', roles: ['admin'], } render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(screen.queryByText('Has Admin:')).not.toBeInTheDocument() expect(screen.queryByText('Has Super User:')).not.toBeInTheDocument() // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(screen.getByText('Has Admin as Array: yes')).toBeInTheDocument() // Log out fireEvent.click(screen.getByText('Log Out')) await waitFor(() => screen.getByText('Log In')) }) test('Checks roles successfully when roles in currentUser is a string', async () => { const mockAuthClient = customTestAuth CURRENT_USER_DATA = { name: 'Peter Pistorius', email: '[email protected]', roles: 'admin', } render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(screen.queryByText('Has Admin:')).not.toBeInTheDocument() expect(screen.queryByText('Has Super User:')).not.toBeInTheDocument() // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(screen.getByText('Has Admin: yes')).toBeInTheDocument() expect(screen.getByText('Has Admin as Array: yes')).toBeInTheDocument() // Log out fireEvent.click(screen.getByText('Log Out')) await waitFor(() => screen.getByText('Log In')) }) /** * Check if assigned one of the roles in an array */ test('Authenticated user has assigned role access as expected', async () => { const mockAuthClient = customTestAuth CURRENT_USER_DATA = { name: 'Peter Pistorius', email: '[email protected]', roles: ['editor'], } render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(screen.queryByText('Has Admin:')).not.toBeInTheDocument() expect(screen.queryByText('Has Super User:')).not.toBeInTheDocument() // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(screen.getByText('Has Editor: yes')).toBeInTheDocument() // Log out fireEvent.click(screen.getByText('Log Out')) await waitFor(() => screen.getByText('Log In')) }) /** * Check if not assigned any of the roles in an array */ test('Authenticated user has assigned role access as expected', async () => { const mockAuthClient = customTestAuth CURRENT_USER_DATA = { name: 'Peter Pistorius', email: '[email protected]', roles: ['admin'], } render( <AuthProvider> <AuthConsumer /> </AuthProvider> ) // We're booting up! expect(screen.getByText('Loading...')).toBeInTheDocument() // The user is not authenticated await waitFor(() => screen.getByText('Log In')) expect(screen.queryByText('Has Admin:')).not.toBeInTheDocument() expect(screen.queryByText('Has Super User:')).not.toBeInTheDocument() // Replace "getUserMetadata" with actual data, and login! mockAuthClient.getUserMetadata = jest.fn(() => { return { sub: 'abcdefg|123456', username: 'peterp', } }) fireEvent.click(screen.getByText('Log In')) // Check that you're logged in! await waitFor(() => screen.getByText('Log Out')) expect(screen.getByText('Has Admin: yes')).toBeInTheDocument() expect(screen.getByText('Has Editor: no')).toBeInTheDocument() expect(screen.getByText('Has Editor or Author: no')).toBeInTheDocument() // Log out fireEvent.click(screen.getByText('Log Out')) await waitFor(() => screen.getByText('Log In')) }) test('proxies forgotPassword() calls to client', async () => { const mockedForgotPassword = jest.spyOn(customTestAuth, 'forgotPassword') mockedForgotPassword.mockImplementation((username: string) => { expect(username).toEqual('username') }) const TestAuthConsumer = () => { const { loading, forgotPassword } = useAuth() useEffect(() => { if (!loading) { forgotPassword('username') } }, [loading, forgotPassword]) return null } render( <AuthProvider> <TestAuthConsumer /> </AuthProvider> ) await waitFor(() => expect(mockedForgotPassword).toBeCalledWith('username')) }) test('proxies resetPassword() calls to client', async () => { customTestAuth.resetPassword = (password: string) => { expect(password).toEqual('password') return true } const auth = await getCustomTestAuth() // act is generally frowned upon in test cases. But it's okay here, see // https://egghead.io/lessons/jest-fix-the-not-wrapped-in-act-warning-when-testing-custom-hooks // plus, we're note rendering anything, so there is nothing to use // `screen.getByText()` etc with to wait for await act(async () => { await auth.resetPassword('password') }) expect.assertions(1) }) test('proxies validateResetToken() calls to client', async () => { customTestAuth.validateResetToken = (resetToken: string | null) => { expect(resetToken).toEqual('12345') return {} } const auth = await getCustomTestAuth() await act(async () => { await auth.validateResetToken('12345') }) expect.assertions(1) }) test("getToken doesn't fail if client throws an error", async () => { customTestAuth.getToken = jest.fn(() => { throw 'Login Required' }) const auth = await getCustomTestAuth() await act(async () => { await auth.getToken() }) expect(customTestAuth.getToken).toBeCalledTimes(1) }) })
4,432
0
petrpan-code/redwoodjs/redwood/packages
petrpan-code/redwoodjs/redwood/packages/babel-config/dist.test.ts
import path from 'path' const distPath = path.join(__dirname, 'dist') describe('dist', () => { it('exports', async () => { const mod = await import(path.join(distPath, 'index.js')) expect(mod).toMatchInlineSnapshot(` { "BABEL_PLUGIN_TRANSFORM_RUNTIME_OPTIONS": { "corejs": { "proposals": true, "version": 3, }, "version": "7.23.1", }, "CORE_JS_VERSION": "3.32", "RUNTIME_CORE_JS_VERSION": "7.23.1", "TARGETS_NODE": "18.16", "getApiSideBabelConfigPath": [Function], "getApiSideBabelPlugins": [Function], "getApiSideBabelPresets": [Function], "getApiSideDefaultBabelConfig": [Function], "getCommonPlugins": [Function], "getPathsFromConfig": [Function], "getRouteHookBabelPlugins": [Function], "getWebSideBabelConfigPath": [Function], "getWebSideBabelPlugins": [Function], "getWebSideBabelPresets": [Function], "getWebSideDefaultBabelConfig": [Function], "getWebSideOverrides": [Function], "parseTypeScriptConfigFiles": [Function], "prebuildApiFile": [Function], "prebuildWebFile": [Function], "registerApiSideBabelHook": [Function], "registerBabel": [Function], "registerWebSideBabelHook": [Function], "transformWithBabel": [Function], } `) }) })
4,440
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src
petrpan-code/redwoodjs/redwood/packages/babel-config/src/__tests__/api.test.ts
import { vol } from 'memfs' import { getPaths, ensurePosixPath } from '@redwoodjs/project-config' import { getApiSideBabelConfigPath, getApiSideBabelPlugins, getApiSideBabelPresets, TARGETS_NODE, } from '../api' jest.mock('fs', () => require('memfs').fs) const redwoodProjectPath = '/redwood-app' process.env.RWJS_CWD = redwoodProjectPath afterEach(() => { vol.reset() }) describe('api', () => { test("TARGETS_NODE hasn't unintentionally changed", () => { expect(TARGETS_NODE).toMatchInlineSnapshot(`"18.16"`) }) describe('getApiSideBabelPresets', () => { it('only includes `@babel/preset-typescript` by default', () => { const apiSideBabelPresets = getApiSideBabelPresets() expect(apiSideBabelPresets).toMatchInlineSnapshot(` [ [ "@babel/preset-typescript", { "allExtensions": true, "isTSX": true, }, "rwjs-babel-preset-typescript", ], ] `) }) it('can include `@babel/preset-env`', () => { const apiSideBabelPresets = getApiSideBabelPresets({ presetEnv: true }) expect(apiSideBabelPresets).toMatchInlineSnapshot(` [ [ "@babel/preset-typescript", { "allExtensions": true, "isTSX": true, }, "rwjs-babel-preset-typescript", ], [ "@babel/preset-env", { "corejs": { "proposals": true, "version": "3.33", }, "exclude": [ "@babel/plugin-transform-class-properties", "@babel/plugin-transform-private-methods", ], "targets": { "node": "18.16", }, "useBuiltIns": "usage", }, ], ] `) }) }) describe('getApiSideBabelConfigPath', () => { it("gets babel.config.js if it's there", () => { vol.fromNestedJSON( { 'redwood.toml': '', api: { 'babel.config.js': '', }, }, redwoodProjectPath ) const apiSideBabelConfigPath = getApiSideBabelConfigPath() expect(ensurePosixPath(apiSideBabelConfigPath)).toMatch( '/redwood-app/api/babel.config.js' ) }) it("returns undefined if it's not there", () => { vol.fromNestedJSON( { 'redwood.toml': '', api: {}, }, redwoodProjectPath ) const apiSideBabelConfigPath = getApiSideBabelConfigPath() expect(apiSideBabelConfigPath).toBeUndefined() }) }) describe('getApiSideBabelPlugins', () => { it('returns babel plugins', () => { vol.fromNestedJSON( { 'redwood.toml': '', api: {}, }, redwoodProjectPath ) const apiSideBabelPlugins = getApiSideBabelPlugins() expect(apiSideBabelPlugins).toHaveLength(10) const pluginNames = apiSideBabelPlugins.map(([name]) => name) expect(pluginNames).toMatchInlineSnapshot(` [ "@babel/plugin-transform-class-properties", "@babel/plugin-transform-private-methods", "@babel/plugin-transform-private-property-in-object", "@babel/plugin-transform-react-jsx", "@babel/plugin-transform-runtime", "babel-plugin-module-resolver", [Function], "babel-plugin-auto-import", "babel-plugin-graphql-tag", [Function], ] `) const pluginAliases = getPluginAliases(apiSideBabelPlugins) expect(pluginAliases).toMatchInlineSnapshot(` [ "rwjs-api-module-resolver", "rwjs-babel-directory-named-modules", "rwjs-babel-auto-import", "rwjs-babel-graphql-tag", "rwjs-babel-glob-import-dir", ] `) expect(apiSideBabelPlugins).toContainEqual([ '@babel/plugin-transform-class-properties', { loose: true, }, ]) expect(apiSideBabelPlugins).toContainEqual([ '@babel/plugin-transform-private-methods', { loose: true, }, ]) expect(apiSideBabelPlugins).toContainEqual([ '@babel/plugin-transform-private-property-in-object', { loose: true, }, ]) expect(apiSideBabelPlugins).toContainEqual([ '@babel/plugin-transform-runtime', { corejs: { proposals: true, version: 3, }, version: '7.23.4', }, ]) expect(apiSideBabelPlugins).toContainEqual([ '@babel/plugin-transform-react-jsx', { runtime: 'automatic', }, ]) const [_, babelPluginModuleResolverConfig] = apiSideBabelPlugins.find( (plugin) => plugin[0] === 'babel-plugin-module-resolver' ) expect(babelPluginModuleResolverConfig).toMatchObject({ alias: { src: './src', }, cwd: 'packagejson', loglevel: 'silent', // to silence the unnecessary warnings }) expect(babelPluginModuleResolverConfig.root[0]).toMatch( getPaths().api.base ) expect(apiSideBabelPlugins).toContainEqual([ 'babel-plugin-auto-import', { declarations: [ { default: 'gql', path: 'graphql-tag', }, { members: ['context'], path: '@redwoodjs/graphql-server', }, ], }, 'rwjs-babel-auto-import', ]) }) it('can include openTelemetry', () => { vol.fromNestedJSON( { 'redwood.toml': '', api: {}, }, redwoodProjectPath ) const apiSideBabelPlugins = getApiSideBabelPlugins({ openTelemetry: true, }) const pluginAliases = getPluginAliases(apiSideBabelPlugins) expect(pluginAliases).toContain('rwjs-babel-otel-wrapping') }) }) }) function getPluginAliases(plugins) { return plugins.reduce((pluginAliases, plugin) => { if (plugin.length !== 3) { return pluginAliases } return [...pluginAliases, plugin[2]] }, []) }
4,441
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src
petrpan-code/redwoodjs/redwood/packages/babel-config/src/__tests__/common.test.ts
import { vol } from 'memfs' import { ensurePosixPath } from '@redwoodjs/project-config' import { getCommonPlugins, getPathsFromTypeScriptConfig, parseTypeScriptConfigFiles, } from '../common' jest.mock('fs', () => require('memfs').fs) const redwoodProjectPath = '/redwood-app' process.env.RWJS_CWD = redwoodProjectPath afterEach(() => { vol.reset() }) describe('common', () => { it("common plugins haven't changed unintentionally", () => { const commonPlugins = getCommonPlugins() expect(commonPlugins).toMatchInlineSnapshot(` [ [ "@babel/plugin-transform-class-properties", { "loose": true, }, ], [ "@babel/plugin-transform-private-methods", { "loose": true, }, ], [ "@babel/plugin-transform-private-property-in-object", { "loose": true, }, ], ] `) }) describe('TypeScript config files', () => { it("returns `null` if it can't find TypeScript config files", () => { vol.fromNestedJSON( { 'redwood.toml': '', api: {}, web: {}, }, redwoodProjectPath ) const typeScriptConfig = parseTypeScriptConfigFiles() expect(typeScriptConfig).toHaveProperty('api', null) expect(typeScriptConfig).toHaveProperty('web', null) }) it('finds and parses tsconfig.json files', () => { const apiTSConfig = '{"compilerOptions": {"noEmit": true}}' const webTSConfig = '{"compilerOptions": {"allowJs": true}}' vol.fromNestedJSON( { 'redwood.toml': '', api: { 'tsconfig.json': apiTSConfig, }, web: { 'tsconfig.json': webTSConfig, }, }, redwoodProjectPath ) const typeScriptConfig = parseTypeScriptConfigFiles() expect(typeScriptConfig.api).toMatchObject(JSON.parse(apiTSConfig)) expect(typeScriptConfig.web).toMatchObject(JSON.parse(webTSConfig)) }) it('finds and parses jsconfig.json files', () => { const apiJSConfig = '{"compilerOptions": {"noEmit": true}}' const webJSConfig = '{"compilerOptions": {"allowJs": true}}' vol.fromNestedJSON( { 'redwood.toml': '', api: { 'jsconfig.json': apiJSConfig, }, web: { 'jsconfig.json': webJSConfig, }, }, redwoodProjectPath ) const typeScriptConfig = parseTypeScriptConfigFiles() expect(typeScriptConfig.api).toMatchObject(JSON.parse(apiJSConfig)) expect(typeScriptConfig.web).toMatchObject(JSON.parse(webJSConfig)) }) describe('getPathsFromTypeScriptConfig', () => { it("returns an empty object if there's no TypeScript config files", () => { vol.fromNestedJSON( { 'redwood.toml': '', api: {}, web: {}, }, redwoodProjectPath ) const typeScriptConfig = parseTypeScriptConfigFiles() const apiPaths = getPathsFromTypeScriptConfig(typeScriptConfig.api) expect(apiPaths).toMatchObject({}) const webPaths = getPathsFromTypeScriptConfig(typeScriptConfig.web) expect(webPaths).toMatchObject({}) }) it("returns an empty object if there's no compilerOptions, baseUrl, or paths", () => { const apiTSConfig = '{}' const webTSConfig = '{"compilerOptions":{"allowJs": true}}' vol.fromNestedJSON( { 'redwood.toml': '', api: { 'tsconfig.json': apiTSConfig, }, web: { 'tsconfig.json': webTSConfig, }, }, redwoodProjectPath ) const typeScriptConfig = parseTypeScriptConfigFiles() const apiPaths = getPathsFromTypeScriptConfig(typeScriptConfig.api) expect(apiPaths).toMatchInlineSnapshot(`{}`) const webPaths = getPathsFromTypeScriptConfig(typeScriptConfig.web) expect(webPaths).toMatchInlineSnapshot(`{}`) }) it('excludes "src/*", "$api/*", "types/*", and "@redwoodjs/testing"', () => { const apiTSConfig = '{"compilerOptions":{"baseUrl":"./","paths":{"src/*":["./src/*","../.redwood/types/mirror/api/src/*"],"types/*":["./types/*","../types/*"],"@redwoodjs/testing":["../node_modules/@redwoodjs/testing/api"]}}}' const webTSConfig = '{"compilerOptions":{"baseUrl":"./","paths":{"src/*":["./src/*","../.redwood/types/mirror/web/src/*"],"$api/*":[ "../api/*" ],"types/*":["./types/*", "../types/*"],"@redwoodjs/testing":["../node_modules/@redwoodjs/testing/web"]}}}' vol.fromNestedJSON( { 'redwood.toml': '', api: { 'tsconfig.json': apiTSConfig, }, web: { 'tsconfig.json': webTSConfig, }, }, redwoodProjectPath ) const typeScriptConfig = parseTypeScriptConfigFiles() const apiPaths = getPathsFromTypeScriptConfig(typeScriptConfig.api) expect(apiPaths).toMatchInlineSnapshot(`{}`) const webPaths = getPathsFromTypeScriptConfig(typeScriptConfig.web) expect(webPaths).toMatchInlineSnapshot(`{}`) }) it('gets and formats paths', () => { const apiTSConfig = '{"compilerOptions":{"baseUrl":"./","paths":{"@services/*":["./src/services/*"]}}}' const webTSConfig = '{"compilerOptions":{"baseUrl":"./","paths":{"@ui/*":["./src/ui/*"]}}}' vol.fromNestedJSON( { 'redwood.toml': '', api: { 'tsconfig.json': apiTSConfig, }, web: { 'tsconfig.json': webTSConfig, }, }, redwoodProjectPath ) const typeScriptConfig = parseTypeScriptConfigFiles() const apiPaths = getPathsFromTypeScriptConfig(typeScriptConfig.api) expect(ensurePosixPath(apiPaths['@services'])).toMatchInlineSnapshot( `"src/services"` ) const webPaths = getPathsFromTypeScriptConfig(typeScriptConfig.web) expect(ensurePosixPath(webPaths['@ui'])).toMatchInlineSnapshot( `"src/ui"` ) }) }) it('handles invalid JSON', () => { const apiTSConfig = '{"compilerOptions": {"noEmit": true,"allowJs": true,"esModuleInterop": true,"target": "esnext","module": "esnext","moduleResolution": "node","baseUrl": "./","rootDirs": ["./src","../.redwood/types/mirror/api/src"],"paths": {"src/*": ["./src/*","../.redwood/types/mirror/api/src/*"],"types/*": ["./types/*", "../types/*"],"@redwoodjs/testing": ["../node_modules/@redwoodjs/testing/api"]},"typeRoots": ["../node_modules/@types","./node_modules/@types"],"types": ["jest"],},"include": ["src","../.redwood/types/includes/all-*","../.redwood/types/includes/api-*","../types"]}' const webTSConfig = '{"compilerOptions": {"noEmit": true,"allowJs": true,"esModuleInterop": true,"target": "esnext","module": "esnext","moduleResolution": "node","baseUrl": "./","rootDirs": ["./src","../.redwood/types/mirror/web/src","../api/src","../.redwood/types/mirror/api/src"],"paths": {"src/*": ["./src/*","../.redwood/types/mirror/web/src/*","../api/src/*","../.redwood/types/mirror/api/src/*"],"$api/*": [ "../api/*" ],"types/*": ["./types/*", "../types/*"],"@redwoodjs/testing": ["../node_modules/@redwoodjs/testing/web"]},"typeRoots": ["../node_modules/@types", "./node_modules/@types"],"types": ["jest", "@testing-library/jest-dom"],"jsx": "preserve",},"include": ["src","../.redwood/types/includes/all-*","../.redwood/types/includes/web-*","../types","./types"]}' vol.fromNestedJSON( { 'redwood.toml': '', api: { 'tsconfig.json': apiTSConfig, }, web: { 'tsconfig.json': webTSConfig, }, }, redwoodProjectPath ) expect(parseTypeScriptConfigFiles).not.toThrow() }) }) })
4,442
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src
petrpan-code/redwoodjs/redwood/packages/babel-config/src/__tests__/prebuildApiFile.test.ts
import path from 'path' import compat from 'core-js-compat' import { getPaths, getConfig } from '@redwoodjs/project-config' import { BABEL_PLUGIN_TRANSFORM_RUNTIME_OPTIONS, getApiSideBabelPlugins, prebuildApiFile, TARGETS_NODE, } from '../api' const RWJS_CWD = path.join(__dirname, '__fixtures__/redwood-app') process.env.RWJS_CWD = RWJS_CWD let code describe('api prebuild ', () => { describe('polyfills unsupported functionality', () => { beforeAll(() => { const apiFile = path.join(RWJS_CWD, 'api/src/lib/polyfill.js') code = prebuildApiFileWrapper(apiFile) }) describe('ES features', () => { describe('Node.js 13', () => { it('polyfills Math.hypot', () => { expect(code).toContain( `import _Math$hypot from "@babel/runtime-corejs3/core-js/math/hypot"` ) }) }) describe('Node.js 14', () => { it('polyfills String.matchAll', () => { expect(code).toContain( `import _matchAllInstanceProperty from "@babel/runtime-corejs3/core-js/instance/match-all"` ) }) }) describe('Node.js 15', () => { it('polyfills AggregateError', () => { expect(code).toContain( `import _AggregateError from "@babel/runtime-corejs3/core-js/aggregate-error"` ) }) // The reason we're testing it this way is that core-js polyfills the entire Promise built in. // // So this... // // ```js // Promise.any([ // Promise.resolve(1), // Promise.reject(2), // Promise.resolve(3), // ]).then(console.log) // // ↓↓↓ // // import _Promise from "@babel/runtime-corejs3/core-js/promise"; // // _Promise.any([ // _Promise.resolve(1), // _Promise.reject(2), // _Promise.resolve(3)]) // .then(console.log); // ``` // // Compared to the Reflect polyfills, which only polyfill the method used, // just checking that the Promise polyfill is imported isn't enough: // // ```js // Reflect.defineMetadata(metadataKey, metadataValue, target) // // ↓↓↓ // // import _Reflect$defineMetadata from "@babel/runtime-corejs3/core-js/reflect/define-metadata"; // _Reflect$defineMetadata(metadataKey, metadataValue, target); // ``` it('polyfills Promise.any', () => { expect(code).toContain( `import _Promise from "@babel/runtime-corejs3/core-js/promise"` ) const _Promise = require('@babel/runtime-corejs3/core-js/promise') expect(_Promise).toHaveProperty('any') }) it('polyfills String.replaceAll', () => { expect(code).toContain( `import _replaceAllInstanceProperty from "@babel/runtime-corejs3/core-js/instance/replace-all"` ) }) }) describe('Node.js 17', () => { // core-js-pure overrides this. See https://github.com/zloirock/core-js/blob/master/packages/core-js-pure/override/modules/es.typed-array.set.js. it("doesn't polyfill TypedArray.set", () => { expect(code).toContain( [ `const buffer = new ArrayBuffer(8);`, `const uint8 = new Uint8Array(buffer);`, `uint8.set([1, 2, 3], 3);`, ].join('\n') ) }) }) }) describe('ES Next features', () => { describe('Pre-stage 0 proposals', () => { // Reflect metadata // See https://github.com/zloirock/core-js#reflect-metadata it('polyfills Reflect methods', () => { expect(code).toContain( `import _Reflect$defineMetadata from "@babel/runtime-corejs3/core-js/reflect/define-metadata"` ) expect(code).toContain( `import _Reflect$deleteMetadata from "@babel/runtime-corejs3/core-js/reflect/delete-metadata"` ) expect(code).toContain( `import _Reflect$getMetadata from "@babel/runtime-corejs3/core-js/reflect/get-metadata"` ) expect(code).toContain( `import _Reflect$getMetadataKeys from "@babel/runtime-corejs3/core-js/reflect/get-metadata-keys"` ) expect(code).toContain( `import _Reflect$getOwnMetadata from "@babel/runtime-corejs3/core-js/reflect/get-own-metadata"` ) expect(code).toContain( `import _Reflect$getOwnMetadataKeys from "@babel/runtime-corejs3/core-js/reflect/get-own-metadata-keys"` ) expect(code).toContain( `import _Reflect$hasMetadata from "@babel/runtime-corejs3/core-js/reflect/has-metadata"` ) expect(code).toContain( `import _Reflect$hasOwnMetadata from "@babel/runtime-corejs3/core-js/reflect/has-own-metadata"` ) expect(code).toContain( `import _Reflect$metadata from "@babel/runtime-corejs3/core-js/reflect/metadata"` ) }) }) describe('Stage 1 proposals', () => { // Getting last item from Array // See https://github.com/zloirock/core-js#getting-last-item-from-array // // core-js-pure overrides these. See... // - https://github.com/zloirock/core-js/blob/master/packages/core-js-pure/override/modules/esnext.array.last-index.js, // - https://github.com/zloirock/core-js/blob/master/packages/core-js-pure/override/modules/esnext.array.last-item.js it("doesn't polyfill Getting last item from Array", () => { expect(code).toContain( [ `[1, 2, 3].lastIndex;`, `[1, 2, 3].lastItem;`, `const array = [1, 2, 3];`, `array.lastItem = 4;`, `new Array(1, 2, 3).lastIndex;`, `new Array(1, 2, 3).lastItem;`, ].join('\n') ) }) // compositeKey and compositeSymbol // See https://github.com/zloirock/core-js#compositekey-and-compositesymbol it('polyfills compositeKey and compositeSymbol', () => { expect(code).toContain( `import _compositeKey from "@babel/runtime-corejs3/core-js/composite-key"` ) expect(code).toContain( `import _compositeSymbol from "@babel/runtime-corejs3/core-js/composite-symbol"` ) }) // New collections methods // See https://github.com/zloirock/core-js#new-collections-methods it('polyfills New collections methods', () => { expect(code).toContain( `import _Map from "@babel/runtime-corejs3/core-js/map"` ) // See the comments on Promise.any above for more of an explanation // of why we're testing for properties. const _Map = require('@babel/runtime-corejs3/core-js/map') expect(_Map).toHaveProperty('deleteAll') expect(_Map).toHaveProperty('every') expect(_Map).toHaveProperty('filter') expect(_Map).toHaveProperty('find') expect(_Map).toHaveProperty('findKey') expect(_Map).toHaveProperty('from') expect(_Map).toHaveProperty('groupBy') expect(_Map).toHaveProperty('includes') expect(_Map).toHaveProperty('keyBy') expect(_Map).toHaveProperty('keyOf') expect(_Map).toHaveProperty('mapKeys') expect(_Map).toHaveProperty('mapValues') expect(_Map).toHaveProperty('merge') expect(_Map).toHaveProperty('of') expect(_Map).toHaveProperty('reduce') expect(_Map).toHaveProperty('some') expect(_Map).toHaveProperty('update') expect(code).toContain( `import _Set from "@babel/runtime-corejs3/core-js/set"` ) const _Set = require('@babel/runtime-corejs3/core-js/set') expect(_Set).toHaveProperty('addAll') expect(_Set).toHaveProperty('deleteAll') expect(_Set).toHaveProperty('difference') expect(_Set).toHaveProperty('every') expect(_Set).toHaveProperty('filter') expect(_Set).toHaveProperty('find') expect(_Set).toHaveProperty('from') expect(_Set).toHaveProperty('intersection') expect(_Set).toHaveProperty('isDisjointFrom') expect(_Set).toHaveProperty('isSubsetOf') expect(_Set).toHaveProperty('isSupersetOf') expect(_Set).toHaveProperty('join') expect(_Set).toHaveProperty('map') expect(_Set).toHaveProperty('of') expect(_Set).toHaveProperty('reduce') expect(_Set).toHaveProperty('some') expect(_Set).toHaveProperty('symmetricDifference') expect(_Set).toHaveProperty('union') expect(code).toContain( `import _WeakMap from "@babel/runtime-corejs3/core-js/weak-map"` ) const _WeakMap = require('@babel/runtime-corejs3/core-js/weak-map') expect(_WeakMap).toHaveProperty('deleteAll') expect(_WeakMap).toHaveProperty('from') expect(_WeakMap).toHaveProperty('of') expect(code).toContain( `import _WeakSet from "@babel/runtime-corejs3/core-js/weak-set"` ) const _WeakSet = require('@babel/runtime-corejs3/core-js/weak-set') expect(_WeakSet).toHaveProperty('addAll') expect(_WeakSet).toHaveProperty('deleteAll') expect(_WeakSet).toHaveProperty('from') expect(_WeakSet).toHaveProperty('of') }) // Math extensions // See https://github.com/zloirock/core-js#math-extensions it('polyfills Math extensions', () => { expect(code).toContain( `import _Math$clamp from "@babel/runtime-corejs3/core-js/math/clamp"` ) expect(code).toContain( `import _Math$DEG_PER_RAD from "@babel/runtime-corejs3/core-js/math/deg-per-rad"` ) expect(code).toContain( `import _Math$degrees from "@babel/runtime-corejs3/core-js/math/degrees"` ) expect(code).toContain( `import _Math$fscale from "@babel/runtime-corejs3/core-js/math/fscale"` ) expect(code).toContain( `import _Math$RAD_PER_DEG from "@babel/runtime-corejs3/core-js/math/rad-per-deg"` ) expect(code).toContain( `import _Math$radians from "@babel/runtime-corejs3/core-js/math/radians"` ) expect(code).toContain( `import _Math$scale from "@babel/runtime-corejs3/core-js/math/scale"` ) }) // Math.signbit // See https://github.com/zloirock/core-js#mathsignbit it('polyfills Math.signbit', () => { expect(code).toContain( `import _Math$signbit from "@babel/runtime-corejs3/core-js/math/signbit"` ) }) // Number.fromString // See https://github.com/zloirock/core-js#numberfromstring it('polyfills Number.fromString', () => { expect(code).toContain( `import _Number$fromString from "@babel/runtime-corejs3/core-js/number/from-string"` ) }) // Observable // See https://github.com/zloirock/core-js#observable it('polyfills Observable', () => { expect(code).toContain( `import _Observable from "@babel/runtime-corejs3/core-js/observable"` ) expect(code).toContain( `import _Symbol$observable from "@babel/runtime-corejs3/core-js/symbol/observable"` ) }) // String.prototype.codePoints // See https://github.com/zloirock/core-js#stringprototypecodepoints it('polyfills String.prototype.codePoints', () => { expect(code).toContain( `import _codePointsInstanceProperty from "@babel/runtime-corejs3/core-js/instance/code-points"` ) }) // Symbol.matcher for pattern matching // See https://github.com/zloirock/core-js#symbolmatcher-for-pattern-matching // This one's been renamed to Symbol.matcher since core-js v3.0.0. But Symbol.patternMatch still works it('polyfills Symbol.matcher', () => { expect(code).toContain( `import _Symbol$patternMatch from "@babel/runtime-corejs3/core-js/symbol/pattern-match"` ) }) }) describe('Stage 2 proposals', () => { // Symbol.{ asyncDispose, dispose } for using statement // See https://github.com/zloirock/core-js#symbol-asyncdispose-dispose--for-using-statement it('polyfills Symbol.{ asyncDispose, dispose } for using statement', () => { expect(code).toContain( `import _Symbol$dispose from "@babel/runtime-corejs3/core-js/symbol/dispose"` ) }) }) }) describe('Withdrawn proposals (will be removed in core-js 4)', () => { // Efficient 64 bit arithmetic // See https://github.com/zloirock/core-js#efficient-64-bit-arithmetic it('polyfills efficient 64 bit arithmetic', () => { expect(code).toContain( `import _Math$iaddh from "@babel/runtime-corejs3/core-js/math/iaddh"` ) expect(code).toContain( `import _Math$imulh from "@babel/runtime-corejs3/core-js/math/imulh"` ) expect(code).toContain( `import _Math$isubh from "@babel/runtime-corejs3/core-js/math/isubh"` ) expect(code).toContain( `import _Math$umulh from "@babel/runtime-corejs3/core-js/math/umulh"` ) }) // Promise.try // See https://github.com/zloirock/core-js#promisetry it('polyfills Promise.try', () => { const _Promise = require('@babel/runtime-corejs3/core-js/promise') expect(_Promise).toHaveProperty('try') }) // String#at // See https://github.com/zloirock/core-js#stringat it('polyfills String#at', () => { expect(code).toContain( `import _atInstanceProperty from "@babel/runtime-corejs3/core-js/instance/at"` ) }) }) describe('Unstable (will be removed in core-js 4)', () => { // Seeded pseudo-random numbers // See https://github.com/zloirock/core-js#seeded-pseudo-random-numbers it('polyfills Seeded pseudo-random numbers', () => { expect(code).toContain( `import _Math$seededPRNG from "@babel/runtime-corejs3/core-js/math/seeded-prng"` ) }) }) it('includes source maps', () => { const sourceMaps = code.split('\n').pop() const sourceMapsMatcher = '//# sourceMappingURL=data:application/json;charset=utf-8;base64,' expect(sourceMaps).toMatch(sourceMapsMatcher) const [_, base64EncodedFile] = sourceMaps.split(sourceMapsMatcher) const { sources } = JSON.parse( Buffer.from(base64EncodedFile, 'base64').toString('utf-8') ) expect(sources).toMatchInlineSnapshot(` [ "../../../../../api/src/lib/polyfill.js", ] `) }) }) describe('uses core-js3 aliasing', () => { beforeAll(() => { const apiFile = path.join(RWJS_CWD, 'api/src/lib/transform.js') code = prebuildApiFileWrapper(apiFile) }) it('works', () => { // See https://babeljs.io/docs/en/babel-plugin-transform-runtime#core-js-aliasing // This is because we configure the transform runtime plugin corejs // Polyfill for Symbol expect(code).toContain( `import _Symbol from "@babel/runtime-corejs3/core-js/symbol"` ) // Polyfill for Promise expect(code).toContain( `import _Promise from "@babel/runtime-corejs3/core-js/promise"` ) // Polyfill for .includes expect(code).toContain( 'import _includesInstanceProperty from "@babel/runtime-corejs3/core-js/instance/includes"' ) // Polyfill for .iterator expect(code).toContain( `import _getIterator from "@babel/runtime-corejs3/core-js/get-iterator"` ) }) }) describe('typescript', () => { beforeAll(() => { const apiFile = path.join(RWJS_CWD, 'api/src/lib/typescript.ts') code = prebuildApiFileWrapper(apiFile) }) it('transpiles ts to js', () => { expect(code).toContain('const x = 0') expect(code).not.toContain('const x: number = 0') }) }) describe('auto imports', () => { beforeAll(() => { const apiFile = path.join(RWJS_CWD, 'api/src/lib/autoImports.ts') code = prebuildApiFileWrapper(apiFile) }) it('auto imports', () => { expect(code).toContain( 'import { context } from "@redwoodjs/graphql-server"' ) expect(code).toContain('import gql from "graphql-tag"') }) }) test('core-js polyfill list', () => { const { list } = compat({ targets: { node: TARGETS_NODE }, version: BABEL_PLUGIN_TRANSFORM_RUNTIME_OPTIONS.corejs.version, }) /** * Redwood targets Node.js 12, but that doesn't factor into what gets polyfilled * because Redwood uses the plugin-transform-runtime polyfill strategy. * * Also, plugin-transform-runtime is pinned to core-js v3.0.0, * so the list of available polyfill is a little outdated. * Some "ES Next" polyfills have landed in v12+ Node.js versions. */ expect(list).toMatchInlineSnapshot(` [ "es.regexp.flags", "esnext.array.last-index", "esnext.array.last-item", "esnext.composite-key", "esnext.composite-symbol", "esnext.map.delete-all", "esnext.map.every", "esnext.map.filter", "esnext.map.find", "esnext.map.find-key", "esnext.map.from", "esnext.map.group-by", "esnext.map.includes", "esnext.map.key-by", "esnext.map.key-of", "esnext.map.map-keys", "esnext.map.map-values", "esnext.map.merge", "esnext.map.of", "esnext.map.reduce", "esnext.map.some", "esnext.map.update", "esnext.math.clamp", "esnext.math.deg-per-rad", "esnext.math.degrees", "esnext.math.fscale", "esnext.math.iaddh", "esnext.math.imulh", "esnext.math.isubh", "esnext.math.rad-per-deg", "esnext.math.radians", "esnext.math.scale", "esnext.math.seeded-prng", "esnext.math.signbit", "esnext.math.umulh", "esnext.number.from-string", "esnext.observable", "esnext.promise.try", "esnext.reflect.define-metadata", "esnext.reflect.delete-metadata", "esnext.reflect.get-metadata", "esnext.reflect.get-metadata-keys", "esnext.reflect.get-own-metadata", "esnext.reflect.get-own-metadata-keys", "esnext.reflect.has-metadata", "esnext.reflect.has-own-metadata", "esnext.reflect.metadata", "esnext.set.add-all", "esnext.set.delete-all", "esnext.set.difference", "esnext.set.every", "esnext.set.filter", "esnext.set.find", "esnext.set.from", "esnext.set.intersection", "esnext.set.is-disjoint-from", "esnext.set.is-subset-of", "esnext.set.is-superset-of", "esnext.set.join", "esnext.set.map", "esnext.set.of", "esnext.set.reduce", "esnext.set.some", "esnext.set.symmetric-difference", "esnext.set.union", "esnext.string.at", "esnext.string.code-points", "esnext.symbol.dispose", "esnext.symbol.observable", "esnext.symbol.pattern-match", "esnext.weak-map.delete-all", "esnext.weak-map.from", "esnext.weak-map.of", "esnext.weak-set.add-all", "esnext.weak-set.delete-all", "esnext.weak-set.from", "esnext.weak-set.of", ] `) }) }) /** * A copy of prebuildApiFiles from packages/internal/src/build/api.ts * This will be re-architected, but doing so now would introduce breaking changes. */ export const prebuildApiFileWrapper = (srcFile: string) => { const redwoodProjectPaths = getPaths() const plugins = getApiSideBabelPlugins({ openTelemetry: getConfig().experimental.opentelemetry.enabled, }) const relativePathFromSrc = path.relative(redwoodProjectPaths.base, srcFile) const dstPath = path .join(redwoodProjectPaths.generated.prebuild, relativePathFromSrc) .replace(/\.(ts)$/, '.js') const result = prebuildApiFile(srcFile, dstPath, plugins) if (!result?.code) { throw new Error(`Couldn't prebuild ${srcFile}`) } return result.code }
4,458
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-cell.test.ts
import path from 'path' import pluginTester from 'babel-plugin-tester' import redwoodCellPlugin from '../babel-plugin-redwood-cell' pluginTester({ plugin: redwoodCellPlugin, pluginName: 'babel-plugin-redwood-cell', fixtures: path.join(__dirname, '__fixtures__/cell'), })
4,459
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-directory-named-imports.test.ts
import * as babel from '@babel/core' import namedDirectory from '../babel-plugin-redwood-directory-named-import' const testCases = [ // Directory named imports { input: 'import { ImpModule } from "./__fixtures__/directory-named-imports/Module"', output: 'import { ImpModule } from "./__fixtures__/directory-named-imports/Module/Module";', }, // Directory named imports TSX { input: 'import { ImpTSX } from "./__fixtures__/directory-named-imports/TSX"', output: `import { ImpTSX } from "./__fixtures__/directory-named-imports/TSX/TSX";`, }, // Directory named exports { input: 'export { ExpModule } from "./__fixtures__/directory-named-imports/Module"', output: `export { ExpModule } from "./__fixtures__/directory-named-imports/Module/Module";`, }, // Gives preferences to `index.*` { input: 'export { ExpIndex } from "./__fixtures__/directory-named-imports/indexModule"', output: `export { ExpIndex } from "./__fixtures__/directory-named-imports/indexModule/index";`, }, { input: 'export { TSWithIndex } from "./__fixtures__/directory-named-imports/TSWithIndex"', output: `export { TSWithIndex } from "./__fixtures__/directory-named-imports/TSWithIndex/index";`, }, // Supports "*.ts" { input: 'export { pew } from "./__fixtures__/directory-named-imports/TS"', output: `export { pew } from "./__fixtures__/directory-named-imports/TS/TS";`, }, // Supports "*.tsx" { input: 'export { pew } from "./__fixtures__/directory-named-imports/TSX"', output: `export { pew } from "./__fixtures__/directory-named-imports/TSX/TSX";`, }, // Supports "*.jsx" { input: 'export { pew } from "./__fixtures__/directory-named-imports/JSX"', output: `export { pew } from "./__fixtures__/directory-named-imports/JSX/JSX";`, }, ] describe('directory named imports', () => { testCases.forEach(({ input, output }) => { test(`it should resolve ${input} to ${output}`, () => { const babeled = babel.transform(input, { babelrc: false, filename: __filename, // ordinarily provided plugins: [ [ namedDirectory, { rootDir: 'src', // not sure exactly what this means honorIndex: true, }, ], ], }).code expect(babeled).toMatch(output) }) }) })
4,460
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-import-dir.test.ts
import path from 'path' import pluginTester from 'babel-plugin-tester' import plugin from '../babel-plugin-redwood-import-dir' describe('babel plugin redwood import dir', () => { pluginTester({ plugin, pluginName: 'babel-plugin-redwood-import-dir', fixtures: path.join(__dirname, '__fixtures__/import-dir'), }) })
4,461
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-mock-cell-data.test.ts
import path from 'path' import pluginTester from 'babel-plugin-tester' import plugin from '../babel-plugin-redwood-mock-cell-data' describe('babel plugin redwood mock cell data', () => { const __fixtures__ = path.resolve(__dirname, '../../../../../__fixtures__') process.env.RWJS_CWD = path.join(__fixtures__, 'example-todo-main') pluginTester({ plugin, tests: { 'cell with afterQuery': { fixture: path.join( __fixtures__, 'example-todo-main/web/src/components/TodoListCell/TodoListCell.mock.js' ), outputFixture: path.join( __dirname, '__fixtures__/mock-cell-data/output_TodoListCell.mock.js' ), }, 'cell without afterQuery': { fixture: path.join( __fixtures__, 'example-todo-main/web/src/components/NumTodosCell/NumTodosCell.mock.js' ), outputFixture: path.join( __dirname, '__fixtures__/mock-cell-data/output_NumTodosCell.mock.js' ), }, 'exporting a function declaration': { fixture: path.join( __fixtures__, 'example-todo-main/web/src/components/NumTodosTwoCell/NumTodosTwoCell.mock.js' ), outputFixture: path.join( __dirname, '__fixtures__/mock-cell-data/output_NumTodosTwoCell.mock.js' ), }, }, }) })
4,462
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-otel-wrapping.test.ts
import path from 'path' import pluginTester from 'babel-plugin-tester' import redwoodOtelWrappingPlugin from '../babel-plugin-redwood-otel-wrapping' jest.mock('@redwoodjs/project-config', () => { return { getBaseDirFromFile: () => { return '' }, } }) pluginTester({ plugin: redwoodOtelWrappingPlugin, pluginName: 'babel-plugin-redwood-otel-wrapping', fixtures: path.join(__dirname, '__fixtures__/otel-wrapping'), })
4,463
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-remove-dev-fatal-error-page.test.ts
import path from 'path' import pluginTester from 'babel-plugin-tester' import plugin from '../babel-plugin-redwood-remove-dev-fatal-error-page' describe('babel plugin redwood remove dev fatal error page', () => { pluginTester({ plugin, pluginName: 'babel-plugin-redwood-remove-dev-fatal-error-page', fixtures: path.join(__dirname, '__fixtures__/dev-fatal-error-page'), babelOptions: { presets: ['@babel/preset-react'], }, }) })
4,464
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-routes-auto-loader.test.ts
import fs from 'fs' import path from 'path' import * as babel from '@babel/core' import { getPaths } from '@redwoodjs/project-config' import babelRoutesAutoLoader from '../babel-plugin-redwood-routes-auto-loader' const transform = (filename: string) => { const code = fs.readFileSync(filename, 'utf-8') return babel.transform(code, { filename, presets: ['@babel/preset-react'], plugins: [babelRoutesAutoLoader], }) } describe('mulitiple files ending in Page.{js,jsx,ts,tsx}', () => { const FAILURE_FIXTURE_PATH = path.resolve( __dirname, './__fixtures__/route-auto-loader/failure' ) beforeAll(() => { process.env.RWJS_CWD = FAILURE_FIXTURE_PATH }) afterAll(() => { delete process.env.RWJS_CWD }) test('Fails with appropriate message', () => { expect(() => { transform(getPaths().web.routes) }).toThrowError( "Unable to find only a single file ending in 'Page.{js,jsx,ts,tsx}' in the follow page directories: 'HomePage" ) }) }) describe('page auto loader correctly imports pages', () => { const FIXTURE_PATH = path.resolve( __dirname, '../../../../../__fixtures__/example-todo-main/' ) let result: babel.BabelFileResult | null beforeAll(() => { process.env.RWJS_CWD = FIXTURE_PATH result = transform(getPaths().web.routes) }) afterAll(() => { delete process.env.RWJS_CWD }) test('Pages get both a LazyComponent and a prerenderLoader', () => { expect(result?.code).toContain(`const HomePage = { name: "HomePage", prerenderLoader: name => __webpack_require__(require.resolveWeak("./pages/HomePage/HomePage")), LazyComponent: lazy(() => import( /* webpackChunkName: "HomePage" */"./pages/HomePage/HomePage")) `) }) test('Already imported pages are left alone.', () => { expect(result?.code).toContain(`import FooPage from 'src/pages/FooPage'`) }) })
4,465
0
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins
petrpan-code/redwoodjs/redwood/packages/babel-config/src/plugins/__tests__/babel-plugin-redwood-src-alias.test.ts
import path from 'path' import pluginTester from 'babel-plugin-tester' import plugin from '../babel-plugin-redwood-src-alias' const FIXTURE_PATH = path.resolve( __dirname, '../../../../../__fixtures__/empty-project' ) describe('babel plugin redwood import dir - graphql function', () => { pluginTester({ plugin, pluginOptions: { srcAbsPath: path.join(FIXTURE_PATH, 'api/src'), }, pluginName: 'babel-plugin-redwood-src-alias', // We need to set the filename so that state.file.opts.filename is set // See https://github.com/babel-utils/babel-plugin-tester/issues/87 filename: path.join(FIXTURE_PATH, 'api/src/functions/graphql.ts'), tests: { 'transforms auth imports': { code: "import { getCurrentUser } from 'src/lib/auth'", output: "import { getCurrentUser } from '../lib/auth'", }, 'imports prisma instance correctly': { code: "import { db } from 'src/lib/db'", output: "import { db } from '../lib/db'", }, 'kitten utils are correctly found': { code: "import cuddles from 'src/lib/kittens/utils'", output: "import cuddles from '../lib/kittens/utils'", }, }, }) }) describe('Handles import statements from a service too', () => { pluginTester({ plugin, pluginOptions: { srcAbsPath: path.join(FIXTURE_PATH, 'api/src'), }, pluginName: 'babel-plugin-redwood-src-alias', // As if the import statement is in another service filename: path.join(FIXTURE_PATH, 'api/src/services/bazinga/bazinga.ts'), tests: { 'transforms auth imports from service': { code: "import { requireAuth } from 'src/lib/auth'", output: "import { requireAuth } from '../../lib/auth'", }, 'imports from another service': { code: "import posts from 'src/services/posts'", output: "import posts from '../posts'", }, }, }) }) describe('Handles typical web imports', () => { pluginTester({ plugin, pluginOptions: { srcAbsPath: path.join(FIXTURE_PATH, 'web/src'), }, pluginName: 'babel-plugin-redwood-src-alias', // As if the import statement is in another service filename: path.join(FIXTURE_PATH, 'web/src/components/Posts/Post.tsx'), tests: { 'handles imports from another component': { code: "import { QUERY } from 'src/components/Posts/PostsCell'", output: "import { QUERY } from './PostsCell'", }, 'handles imports from utils': { code: "import { cuddles } from 'src/helpers/kittens'", output: "import { cuddles } from '../../helpers/kittens'", }, }, }) })