|
1 | | -import { RequestCookies } from '../cookies' |
| 1 | +import { |
| 2 | + workUnitAsyncStorage, |
| 3 | + type RequestStore, |
| 4 | +} from '../../../app-render/work-unit-async-storage.external' |
| 5 | +import { RequestCookies, ResponseCookies } from '../cookies' |
2 | 6 | import { |
3 | 7 | ReadonlyRequestCookiesError, |
4 | 8 | RequestCookiesAdapter, |
5 | 9 | MutableRequestCookiesAdapter, |
| 10 | + wrapWithMutableAccessCheck, |
6 | 11 | } from './request-cookies' |
7 | 12 |
|
8 | 13 | describe('RequestCookiesAdapter', () => { |
@@ -100,3 +105,50 @@ describe('MutableRequestCookiesAdapter', () => { |
100 | 105 | ]) |
101 | 106 | }) |
102 | 107 | }) |
| 108 | + |
| 109 | +describe('wrapWithMutableAccessCheck', () => { |
| 110 | + const createMockRequestStore = (phase: RequestStore['phase']) => |
| 111 | + ({ type: 'request', phase }) as RequestStore |
| 112 | + |
| 113 | + it('prevents setting cookies in the render phase', () => { |
| 114 | + const requestStore = createMockRequestStore('action') |
| 115 | + workUnitAsyncStorage.run(requestStore, () => { |
| 116 | + const headers = new Headers({}) |
| 117 | + const underlyingCookies = new ResponseCookies(headers) |
| 118 | + const wrappedCookies = wrapWithMutableAccessCheck(underlyingCookies) |
| 119 | + |
| 120 | + // simulate changing phases |
| 121 | + requestStore.phase = 'render' |
| 122 | + |
| 123 | + const EXPECTED_ERROR = |
| 124 | + /Cookies can only be modified in a Server Action or Route Handler\./ |
| 125 | + |
| 126 | + expect(() => { |
| 127 | + wrappedCookies.set('foo', '1') |
| 128 | + }).toThrow(EXPECTED_ERROR) |
| 129 | + |
| 130 | + expect(wrappedCookies.get('foo')).toBe(undefined) |
| 131 | + }) |
| 132 | + }) |
| 133 | + |
| 134 | + it('prevents deleting cookies in the render phase', () => { |
| 135 | + const requestStore = createMockRequestStore('action') |
| 136 | + workUnitAsyncStorage.run(requestStore, () => { |
| 137 | + const headers = new Headers({}) |
| 138 | + const underlyingCookies = new ResponseCookies(headers) |
| 139 | + const wrappedCookies = wrapWithMutableAccessCheck(underlyingCookies) |
| 140 | + wrappedCookies.set('foo', '1') |
| 141 | + |
| 142 | + // simulate changing phases |
| 143 | + requestStore.phase = 'render' |
| 144 | + |
| 145 | + const EXPECTED_ERROR = |
| 146 | + /Cookies can only be modified in a Server Action or Route Handler\./ |
| 147 | + |
| 148 | + expect(() => { |
| 149 | + wrappedCookies.delete('foo') |
| 150 | + }).toThrow(EXPECTED_ERROR) |
| 151 | + expect(wrappedCookies.get('foo')?.value).toEqual('1') |
| 152 | + }) |
| 153 | + }) |
| 154 | +}) |
0 commit comments