@byline/host-tanstack-start 4.0.0 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin-shell/collections/tree-list-projection.d.ts +1 -1
- package/dist/i18n/resolve-locale.js +1 -1
- package/dist/index.d.ts +5 -6
- package/dist/integrations/host-bridge.d.ts +13 -0
- package/dist/integrations/host-bridge.js +22 -0
- package/dist/integrations/serve-uploads.d.ts +1 -0
- package/dist/integrations/serve-uploads.js +1 -0
- package/dist/server-fns/admin-account/change-password.js +1 -1
- package/dist/server-fns/admin-account/get.js +1 -1
- package/dist/server-fns/admin-account/update.js +1 -1
- package/dist/server-fns/admin-activity/get.js +1 -1
- package/dist/server-fns/admin-permissions/get-role-abilities.js +1 -1
- package/dist/server-fns/admin-permissions/list-registered.js +1 -1
- package/dist/server-fns/admin-permissions/set-role-abilities.js +1 -1
- package/dist/server-fns/admin-permissions/who-has.js +1 -1
- package/dist/server-fns/admin-roles/create.js +1 -1
- package/dist/server-fns/admin-roles/delete.js +1 -1
- package/dist/server-fns/admin-roles/get.js +1 -1
- package/dist/server-fns/admin-roles/list.js +1 -1
- package/dist/server-fns/admin-roles/reorder.js +1 -1
- package/dist/server-fns/admin-roles/update.js +1 -1
- package/dist/server-fns/admin-users/create.js +1 -1
- package/dist/server-fns/admin-users/delete.js +1 -1
- package/dist/server-fns/admin-users/disable.js +1 -1
- package/dist/server-fns/admin-users/enable.js +1 -1
- package/dist/server-fns/admin-users/get-user-roles.js +1 -1
- package/dist/server-fns/admin-users/get.js +1 -1
- package/dist/server-fns/admin-users/list.js +1 -1
- package/dist/server-fns/admin-users/set-password.js +1 -1
- package/dist/server-fns/admin-users/set-user-roles.js +1 -1
- package/dist/server-fns/admin-users/update.js +1 -1
- package/dist/server-fns/ai/execute.js +1 -1
- package/dist/server-fns/auth/current-user.js +1 -1
- package/dist/server-fns/auth/sign-in.js +1 -1
- package/dist/server-fns/auth/sign-out.js +1 -2
- package/dist/server-fns/collections/audit.js +1 -1
- package/dist/server-fns/collections/copy-to-locale.js +1 -1
- package/dist/server-fns/collections/create.js +1 -1
- package/dist/server-fns/collections/delete-locale.js +1 -1
- package/dist/server-fns/collections/delete.js +1 -1
- package/dist/server-fns/collections/duplicate.js +1 -1
- package/dist/server-fns/collections/get.js +1 -1
- package/dist/server-fns/collections/history.js +1 -1
- package/dist/server-fns/collections/list.js +1 -1
- package/dist/server-fns/collections/reindex.js +1 -1
- package/dist/server-fns/collections/reorder.js +1 -1
- package/dist/server-fns/collections/restore-version.js +1 -1
- package/dist/server-fns/collections/stats.js +1 -1
- package/dist/server-fns/collections/status.js +1 -1
- package/dist/server-fns/collections/tree.js +1 -1
- package/dist/server-fns/collections/update.js +1 -1
- package/dist/server-fns/collections/upload.js +2 -1
- package/dist/server-fns/i18n/set-locale.js +1 -1
- package/dist/server-fns/preview/disable.js +1 -1
- package/dist/server-fns/preview/enable.js +1 -2
- package/dist/server-fns/preview/state.js +1 -1
- package/package.json +8 -13
- package/src/admin-shell/collections/tree-list-projection.ts +1 -1
- package/src/i18n/resolve-locale.ts +1 -1
- package/src/index.ts +5 -6
- package/src/integrations/host-bridge.ts +56 -0
- package/src/integrations/serve-uploads.ts +6 -0
- package/src/server-fns/admin-account/change-password.ts +1 -1
- package/src/server-fns/admin-account/get.ts +1 -1
- package/src/server-fns/admin-account/update.ts +1 -1
- package/src/server-fns/admin-activity/get.ts +1 -1
- package/src/server-fns/admin-permissions/get-role-abilities.ts +1 -1
- package/src/server-fns/admin-permissions/list-registered.ts +1 -1
- package/src/server-fns/admin-permissions/set-role-abilities.ts +1 -1
- package/src/server-fns/admin-permissions/who-has.ts +1 -1
- package/src/server-fns/admin-roles/create.ts +1 -1
- package/src/server-fns/admin-roles/delete.ts +1 -1
- package/src/server-fns/admin-roles/get.ts +1 -1
- package/src/server-fns/admin-roles/list.ts +1 -1
- package/src/server-fns/admin-roles/reorder.ts +1 -1
- package/src/server-fns/admin-roles/update.ts +1 -1
- package/src/server-fns/admin-users/create.ts +1 -1
- package/src/server-fns/admin-users/delete.ts +1 -1
- package/src/server-fns/admin-users/disable.ts +1 -1
- package/src/server-fns/admin-users/enable.ts +1 -1
- package/src/server-fns/admin-users/get-user-roles.ts +1 -1
- package/src/server-fns/admin-users/get.ts +1 -1
- package/src/server-fns/admin-users/list.ts +1 -1
- package/src/server-fns/admin-users/set-password.ts +1 -1
- package/src/server-fns/admin-users/set-user-roles.ts +1 -1
- package/src/server-fns/admin-users/update.ts +1 -1
- package/src/server-fns/ai/execute.ts +1 -2
- package/src/server-fns/auth/current-user.ts +1 -1
- package/src/server-fns/auth/sign-in.ts +1 -1
- package/src/server-fns/auth/sign-out.ts +5 -3
- package/src/server-fns/collections/audit.ts +1 -1
- package/src/server-fns/collections/copy-to-locale.ts +1 -1
- package/src/server-fns/collections/create.ts +1 -1
- package/src/server-fns/collections/delete-locale.ts +1 -1
- package/src/server-fns/collections/delete.ts +1 -1
- package/src/server-fns/collections/duplicate.ts +1 -1
- package/src/server-fns/collections/get.ts +1 -1
- package/src/server-fns/collections/history.ts +1 -1
- package/src/server-fns/collections/list.ts +1 -1
- package/src/server-fns/collections/reindex.ts +1 -1
- package/src/server-fns/collections/reorder.ts +1 -1
- package/src/server-fns/collections/restore-version.ts +1 -1
- package/src/server-fns/collections/stats.ts +2 -1
- package/src/server-fns/collections/status.ts +1 -1
- package/src/server-fns/collections/tree.ts +2 -2
- package/src/server-fns/collections/update.ts +1 -1
- package/src/server-fns/collections/upload.ts +2 -1
- package/src/server-fns/i18n/set-locale.ts +1 -1
- package/src/server-fns/preview/disable.ts +1 -1
- package/src/server-fns/preview/enable.ts +1 -2
- package/src/server-fns/preview/state.ts +1 -1
- package/dist/auth/auth-context.d.ts +0 -50
- package/dist/auth/auth-context.js +0 -61
- package/dist/auth/auth-cookies.d.ts +0 -34
- package/dist/auth/auth-cookies.js +0 -46
- package/dist/auth/preview-cookies.d.ts +0 -19
- package/dist/auth/preview-cookies.js +0 -26
- package/dist/auth/request-scope.d.ts +0 -16
- package/dist/auth/request-scope.js +0 -24
- package/dist/integrations/byline-client.d.ts +0 -24
- package/dist/integrations/byline-client.js +0 -25
- package/dist/integrations/byline-public-client.d.ts +0 -47
- package/dist/integrations/byline-public-client.js +0 -19
- package/dist/integrations/byline-viewer-client.d.ts +0 -26
- package/dist/integrations/byline-viewer-client.js +0 -44
- package/src/auth/auth-context.test.node.ts +0 -302
- package/src/auth/auth-context.ts +0 -142
- package/src/auth/auth-cookies.ts +0 -113
- package/src/auth/preview-cookies.ts +0 -73
- package/src/auth/request-scope.test.node.ts +0 -93
- package/src/auth/request-scope.ts +0 -62
- package/src/integrations/byline-client.ts +0 -68
- package/src/integrations/byline-public-client.ts +0 -67
- package/src/integrations/byline-viewer-client.ts +0 -111
- package/src/integrations/request-context-contract.test.node.ts +0 -131
- package/src/integrations/request-context-factories.test.node.ts +0 -140
|
@@ -1,302 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* This Source Code is subject to the terms of the Mozilla Public
|
|
3
|
-
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
4
|
-
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
5
|
-
*
|
|
6
|
-
* Copyright (c) Infonomic Company Limited
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Unit coverage for the admin request-context resolver. Mocks the
|
|
11
|
-
* TanStack Start cookie helpers and the `bylineCore.sessionProvider` so
|
|
12
|
-
* the branches can be exercised without a live Postgres or JWT
|
|
13
|
-
* machinery.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
import { AdminAuth, AuthError, AuthErrorCodes } from '@byline/auth'
|
|
17
|
-
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
18
|
-
|
|
19
|
-
// ---------------------------------------------------------------------------
|
|
20
|
-
// Mocks — must be declared before the module under test is imported.
|
|
21
|
-
// `vi.mock` is hoisted to the top of the file, so the fakes themselves
|
|
22
|
-
// have to go through `vi.hoisted` to be available when the factory runs.
|
|
23
|
-
// ---------------------------------------------------------------------------
|
|
24
|
-
|
|
25
|
-
const mocks = vi.hoisted(() => ({
|
|
26
|
-
verifyAccessToken: vi.fn(),
|
|
27
|
-
refreshSession: vi.fn(),
|
|
28
|
-
getCookie: vi.fn(),
|
|
29
|
-
setCookie: vi.fn(),
|
|
30
|
-
getRequestHeader: vi.fn(),
|
|
31
|
-
getRequest: vi.fn(),
|
|
32
|
-
}))
|
|
33
|
-
|
|
34
|
-
vi.mock('@byline/core', async () => {
|
|
35
|
-
const actual = await vi.importActual<typeof import('@byline/core')>('@byline/core')
|
|
36
|
-
return {
|
|
37
|
-
...actual,
|
|
38
|
-
getServerConfig: () => ({
|
|
39
|
-
sessionProvider: {
|
|
40
|
-
verifyAccessToken: mocks.verifyAccessToken,
|
|
41
|
-
refreshSession: mocks.refreshSession,
|
|
42
|
-
},
|
|
43
|
-
}),
|
|
44
|
-
}
|
|
45
|
-
})
|
|
46
|
-
|
|
47
|
-
vi.mock('@tanstack/react-start/server', () => ({
|
|
48
|
-
getCookie: mocks.getCookie,
|
|
49
|
-
setCookie: mocks.setCookie,
|
|
50
|
-
getRequestHeader: mocks.getRequestHeader,
|
|
51
|
-
getRequest: mocks.getRequest,
|
|
52
|
-
}))
|
|
53
|
-
|
|
54
|
-
const { verifyAccessToken, refreshSession, getCookie, setCookie } = mocks
|
|
55
|
-
|
|
56
|
-
// Import AFTER mocks are declared.
|
|
57
|
-
import { getAdminRequestContext } from './auth-context.js'
|
|
58
|
-
|
|
59
|
-
// ---------------------------------------------------------------------------
|
|
60
|
-
|
|
61
|
-
function cookiesReturn(values: Record<string, string | undefined>) {
|
|
62
|
-
getCookie.mockImplementation((name: string) => values[name])
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
function stubActor() {
|
|
66
|
-
return new AdminAuth({
|
|
67
|
-
id: 'admin-1',
|
|
68
|
-
abilities: ['collections.pages.read'],
|
|
69
|
-
})
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
describe('getAdminRequestContext', () => {
|
|
73
|
-
beforeEach(() => {
|
|
74
|
-
vi.clearAllMocks()
|
|
75
|
-
// Default: no Start request in scope, so every call resolves fresh.
|
|
76
|
-
// The per-request memoization tests below override this with a
|
|
77
|
-
// stable request object.
|
|
78
|
-
mocks.getRequest.mockImplementation(() => {
|
|
79
|
-
throw new Error('No StartEvent found in AsyncLocalStorage')
|
|
80
|
-
})
|
|
81
|
-
})
|
|
82
|
-
|
|
83
|
-
afterEach(() => {
|
|
84
|
-
vi.clearAllMocks()
|
|
85
|
-
})
|
|
86
|
-
|
|
87
|
-
it('returns the actor directly when the access token verifies', async () => {
|
|
88
|
-
cookiesReturn({
|
|
89
|
-
byline_access_token: 'valid-access',
|
|
90
|
-
byline_refresh_token: 'some-refresh',
|
|
91
|
-
})
|
|
92
|
-
const actor = stubActor()
|
|
93
|
-
verifyAccessToken.mockResolvedValueOnce({ actor })
|
|
94
|
-
|
|
95
|
-
const ctx = await getAdminRequestContext()
|
|
96
|
-
|
|
97
|
-
expect(ctx.actor).toBe(actor)
|
|
98
|
-
expect(ctx.readMode).toBe('any')
|
|
99
|
-
expect(refreshSession).not.toHaveBeenCalled()
|
|
100
|
-
expect(setCookie).not.toHaveBeenCalled()
|
|
101
|
-
})
|
|
102
|
-
|
|
103
|
-
it('refreshes when the access token fails verification', async () => {
|
|
104
|
-
cookiesReturn({
|
|
105
|
-
byline_access_token: 'stale-access',
|
|
106
|
-
byline_refresh_token: 'valid-refresh',
|
|
107
|
-
})
|
|
108
|
-
const actor = stubActor()
|
|
109
|
-
verifyAccessToken.mockRejectedValueOnce(new Error('expired')).mockResolvedValueOnce({ actor })
|
|
110
|
-
refreshSession.mockResolvedValueOnce({
|
|
111
|
-
accessToken: 'fresh-access',
|
|
112
|
-
refreshToken: 'fresh-refresh',
|
|
113
|
-
accessTokenExpiresAt: new Date(Date.now() + 15 * 60_000),
|
|
114
|
-
refreshTokenExpiresAt: new Date(Date.now() + 30 * 24 * 60 * 60_000),
|
|
115
|
-
})
|
|
116
|
-
|
|
117
|
-
const ctx = await getAdminRequestContext()
|
|
118
|
-
|
|
119
|
-
expect(ctx.actor).toBe(actor)
|
|
120
|
-
expect(refreshSession).toHaveBeenCalledWith({ refreshToken: 'valid-refresh' })
|
|
121
|
-
// Both access + refresh cookies should have been written with maxAge > 0.
|
|
122
|
-
expect(setCookie).toHaveBeenCalledTimes(2)
|
|
123
|
-
const accessCall = setCookie.mock.calls.find((c) => c[0] === 'byline_access_token')
|
|
124
|
-
expect(accessCall?.[1]).toBe('fresh-access')
|
|
125
|
-
expect(accessCall?.[2]?.maxAge).toBeGreaterThan(0)
|
|
126
|
-
})
|
|
127
|
-
|
|
128
|
-
it('refreshes when the access cookie is missing but a refresh cookie exists', async () => {
|
|
129
|
-
cookiesReturn({ byline_refresh_token: 'only-refresh' })
|
|
130
|
-
const actor = stubActor()
|
|
131
|
-
refreshSession.mockResolvedValueOnce({
|
|
132
|
-
accessToken: 'fresh-access',
|
|
133
|
-
refreshToken: 'fresh-refresh',
|
|
134
|
-
accessTokenExpiresAt: new Date(Date.now() + 15 * 60_000),
|
|
135
|
-
refreshTokenExpiresAt: new Date(Date.now() + 30 * 24 * 60 * 60_000),
|
|
136
|
-
})
|
|
137
|
-
verifyAccessToken.mockResolvedValueOnce({ actor })
|
|
138
|
-
|
|
139
|
-
const ctx = await getAdminRequestContext()
|
|
140
|
-
|
|
141
|
-
expect(ctx.actor).toBe(actor)
|
|
142
|
-
// The access-token path was skipped (no cookie) so verifyAccessToken ran
|
|
143
|
-
// only for the freshly-issued token.
|
|
144
|
-
expect(verifyAccessToken).toHaveBeenCalledTimes(1)
|
|
145
|
-
expect(verifyAccessToken).toHaveBeenCalledWith('fresh-access')
|
|
146
|
-
})
|
|
147
|
-
|
|
148
|
-
it('throws ERR_UNAUTHENTICATED without emitting Set-Cookie when no cookies are sent', async () => {
|
|
149
|
-
cookiesReturn({})
|
|
150
|
-
|
|
151
|
-
try {
|
|
152
|
-
await getAdminRequestContext()
|
|
153
|
-
expect.fail('expected ERR_UNAUTHENTICATED')
|
|
154
|
-
} catch (err) {
|
|
155
|
-
expect(err).toBeInstanceOf(AuthError)
|
|
156
|
-
expect((err as AuthError).code).toBe(AuthErrorCodes.UNAUTHENTICATED)
|
|
157
|
-
}
|
|
158
|
-
// Anonymous visitors must produce zero Set-Cookie headers so shared
|
|
159
|
-
// caches (Cloudflare) can cache public pages — a Set-Cookie on the
|
|
160
|
-
// response is a hard bypass signal for CDNs.
|
|
161
|
-
expect(setCookie).not.toHaveBeenCalled()
|
|
162
|
-
})
|
|
163
|
-
|
|
164
|
-
it('clears the stale access cookie when only an access token was sent', async () => {
|
|
165
|
-
cookiesReturn({ byline_access_token: 'stale' })
|
|
166
|
-
verifyAccessToken.mockRejectedValueOnce(new Error('expired'))
|
|
167
|
-
|
|
168
|
-
try {
|
|
169
|
-
await getAdminRequestContext()
|
|
170
|
-
expect.fail('expected ERR_UNAUTHENTICATED')
|
|
171
|
-
} catch (err) {
|
|
172
|
-
expect((err as AuthError).code).toBe(AuthErrorCodes.UNAUTHENTICATED)
|
|
173
|
-
}
|
|
174
|
-
const clears = setCookie.mock.calls.filter((c) => c[2]?.maxAge === 0)
|
|
175
|
-
const clearedNames = new Set(clears.map((c) => c[0]))
|
|
176
|
-
expect(clearedNames.has('byline_access_token')).toBe(true)
|
|
177
|
-
expect(clearedNames.has('byline_refresh_token')).toBe(true)
|
|
178
|
-
})
|
|
179
|
-
|
|
180
|
-
it('clears cookies and throws when refresh itself fails', async () => {
|
|
181
|
-
cookiesReturn({
|
|
182
|
-
byline_access_token: 'stale',
|
|
183
|
-
byline_refresh_token: 'bad-refresh',
|
|
184
|
-
})
|
|
185
|
-
verifyAccessToken.mockRejectedValueOnce(new Error('expired'))
|
|
186
|
-
refreshSession.mockRejectedValueOnce(new Error('revoked'))
|
|
187
|
-
|
|
188
|
-
try {
|
|
189
|
-
await getAdminRequestContext()
|
|
190
|
-
expect.fail('expected ERR_UNAUTHENTICATED')
|
|
191
|
-
} catch (err) {
|
|
192
|
-
expect(err).toBeInstanceOf(AuthError)
|
|
193
|
-
expect((err as AuthError).code).toBe(AuthErrorCodes.UNAUTHENTICATED)
|
|
194
|
-
}
|
|
195
|
-
const clears = setCookie.mock.calls.filter((c) => c[2]?.maxAge === 0)
|
|
196
|
-
expect(clears.length).toBe(2)
|
|
197
|
-
})
|
|
198
|
-
|
|
199
|
-
it('clears cookies and throws when the refreshed access token fails to verify', async () => {
|
|
200
|
-
cookiesReturn({
|
|
201
|
-
byline_access_token: 'stale',
|
|
202
|
-
byline_refresh_token: 'valid',
|
|
203
|
-
})
|
|
204
|
-
verifyAccessToken
|
|
205
|
-
.mockRejectedValueOnce(new Error('expired'))
|
|
206
|
-
.mockRejectedValueOnce(new Error('still bad'))
|
|
207
|
-
refreshSession.mockResolvedValueOnce({
|
|
208
|
-
accessToken: 'fresh-but-somehow-bad',
|
|
209
|
-
refreshToken: 'fresh-refresh',
|
|
210
|
-
accessTokenExpiresAt: new Date(Date.now() + 15 * 60_000),
|
|
211
|
-
refreshTokenExpiresAt: new Date(Date.now() + 30 * 24 * 60 * 60_000),
|
|
212
|
-
})
|
|
213
|
-
|
|
214
|
-
try {
|
|
215
|
-
await getAdminRequestContext()
|
|
216
|
-
expect.fail('expected ERR_UNAUTHENTICATED')
|
|
217
|
-
} catch (err) {
|
|
218
|
-
expect((err as AuthError).code).toBe(AuthErrorCodes.UNAUTHENTICATED)
|
|
219
|
-
}
|
|
220
|
-
const clears = setCookie.mock.calls.filter((c) => c[2]?.maxAge === 0)
|
|
221
|
-
expect(clears.length).toBe(2)
|
|
222
|
-
})
|
|
223
|
-
|
|
224
|
-
describe('per-request memoization', () => {
|
|
225
|
-
it('returns the same context instance — and requestId — for every call in one request', async () => {
|
|
226
|
-
mocks.getRequest.mockReturnValue({ id: 'request-a' })
|
|
227
|
-
cookiesReturn({
|
|
228
|
-
byline_access_token: 'valid-access',
|
|
229
|
-
byline_refresh_token: 'some-refresh',
|
|
230
|
-
})
|
|
231
|
-
verifyAccessToken.mockResolvedValue({ actor: stubActor() })
|
|
232
|
-
|
|
233
|
-
const first = await getAdminRequestContext()
|
|
234
|
-
const second = await getAdminRequestContext()
|
|
235
|
-
|
|
236
|
-
// Reads sharing a ReadContext bind one request authority; the token
|
|
237
|
-
// includes requestId, so it must be stable within a request.
|
|
238
|
-
expect(second).toBe(first)
|
|
239
|
-
expect(second.requestId).toBe(first.requestId)
|
|
240
|
-
expect(verifyAccessToken).toHaveBeenCalledTimes(1)
|
|
241
|
-
})
|
|
242
|
-
|
|
243
|
-
it('resolves independently across different requests', async () => {
|
|
244
|
-
cookiesReturn({
|
|
245
|
-
byline_access_token: 'valid-access',
|
|
246
|
-
byline_refresh_token: 'some-refresh',
|
|
247
|
-
})
|
|
248
|
-
verifyAccessToken.mockResolvedValue({ actor: stubActor() })
|
|
249
|
-
|
|
250
|
-
mocks.getRequest.mockReturnValue({ id: 'request-a' })
|
|
251
|
-
const first = await getAdminRequestContext()
|
|
252
|
-
mocks.getRequest.mockReturnValue({ id: 'request-b' })
|
|
253
|
-
const second = await getAdminRequestContext()
|
|
254
|
-
|
|
255
|
-
expect(second).not.toBe(first)
|
|
256
|
-
expect(second.requestId).not.toBe(first.requestId)
|
|
257
|
-
expect(verifyAccessToken).toHaveBeenCalledTimes(2)
|
|
258
|
-
})
|
|
259
|
-
|
|
260
|
-
it('burns at most one refresh rotation per request', async () => {
|
|
261
|
-
mocks.getRequest.mockReturnValue({ id: 'request-a' })
|
|
262
|
-
cookiesReturn({
|
|
263
|
-
byline_access_token: 'stale-access',
|
|
264
|
-
byline_refresh_token: 'valid-refresh',
|
|
265
|
-
})
|
|
266
|
-
const actor = stubActor()
|
|
267
|
-
verifyAccessToken.mockRejectedValueOnce(new Error('expired')).mockResolvedValueOnce({ actor })
|
|
268
|
-
refreshSession.mockResolvedValueOnce({
|
|
269
|
-
accessToken: 'fresh-access',
|
|
270
|
-
refreshToken: 'fresh-refresh',
|
|
271
|
-
accessTokenExpiresAt: new Date(Date.now() + 15 * 60_000),
|
|
272
|
-
refreshTokenExpiresAt: new Date(Date.now() + 30 * 24 * 60 * 60_000),
|
|
273
|
-
})
|
|
274
|
-
|
|
275
|
-
const first = await getAdminRequestContext()
|
|
276
|
-
// A second unmemoized call would re-run the refresh dance against the
|
|
277
|
-
// request's stale cookie — now already rotated — and sign the admin out.
|
|
278
|
-
const second = await getAdminRequestContext()
|
|
279
|
-
|
|
280
|
-
expect(second).toBe(first)
|
|
281
|
-
expect(refreshSession).toHaveBeenCalledTimes(1)
|
|
282
|
-
})
|
|
283
|
-
|
|
284
|
-
it('memoizes the unauthenticated rejection within one request', async () => {
|
|
285
|
-
mocks.getRequest.mockReturnValue({ id: 'request-a' })
|
|
286
|
-
cookiesReturn({
|
|
287
|
-
byline_access_token: 'stale',
|
|
288
|
-
byline_refresh_token: 'bad-refresh',
|
|
289
|
-
})
|
|
290
|
-
verifyAccessToken.mockRejectedValue(new Error('expired'))
|
|
291
|
-
refreshSession.mockRejectedValue(new Error('revoked'))
|
|
292
|
-
|
|
293
|
-
await expect(getAdminRequestContext()).rejects.toMatchObject({
|
|
294
|
-
code: AuthErrorCodes.UNAUTHENTICATED,
|
|
295
|
-
})
|
|
296
|
-
await expect(getAdminRequestContext()).rejects.toMatchObject({
|
|
297
|
-
code: AuthErrorCodes.UNAUTHENTICATED,
|
|
298
|
-
})
|
|
299
|
-
expect(refreshSession).toHaveBeenCalledTimes(1)
|
|
300
|
-
})
|
|
301
|
-
})
|
|
302
|
-
})
|
package/src/auth/auth-context.ts
DELETED
|
@@ -1,142 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* This Source Code is subject to the terms of the Mozilla Public
|
|
3
|
-
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
4
|
-
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
5
|
-
*
|
|
6
|
-
* Copyright (c) Infonomic Company Limited
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Request-scoped auth context for admin server functions.
|
|
11
|
-
*
|
|
12
|
-
* Reads the session cookies, verifies the access token, transparently
|
|
13
|
-
* refreshes when needed, and returns a `RequestContext` carrying the
|
|
14
|
-
* authenticated `AdminAuth`. Every admin server fn calls this as its
|
|
15
|
-
* first step — it is the single point where the admin transport boundary
|
|
16
|
-
* meets the actor/ability machinery.
|
|
17
|
-
*
|
|
18
|
-
* Flow, in order:
|
|
19
|
-
*
|
|
20
|
-
* 1. Read the access cookie.
|
|
21
|
-
* 2. If present, try `sessionProvider.verifyAccessToken`. On success,
|
|
22
|
-
* return the context — no DB write, no cookie churn.
|
|
23
|
-
* 3. On verify failure (or missing access cookie), read the refresh
|
|
24
|
-
* cookie. If present, call `sessionProvider.refreshSession` — this
|
|
25
|
-
* rotates the refresh token atomically and issues a new access
|
|
26
|
-
* token. Write both fresh cookies to the response.
|
|
27
|
-
* 4. Verify the new access token (populate the actor) and return the
|
|
28
|
-
* context.
|
|
29
|
-
* 5. Any failure along the way clears both cookies so the browser
|
|
30
|
-
* stops sending a session the server has already rejected, and
|
|
31
|
-
* throws `ERR_UNAUTHENTICATED`.
|
|
32
|
-
*
|
|
33
|
-
* Burns a refresh-token rotation only when the access token actually
|
|
34
|
-
* fails verification — not on every request. The "one session" UX is
|
|
35
|
-
* the consequence of this helper working invisibly behind each call.
|
|
36
|
-
*
|
|
37
|
-
* Resolution is memoized per request (`oncePerRequest`): every call within
|
|
38
|
-
* one logical request returns the same `RequestContext` instance — same
|
|
39
|
-
* actor snapshot, same `requestId`. Two invariants depend on this:
|
|
40
|
-
*
|
|
41
|
-
* - The read-authorization layer binds each `ReadContext` to one
|
|
42
|
-
* immutable authority token that includes `requestId`; a fresh id per
|
|
43
|
-
* call makes any two reads sharing a `ReadContext` (the admin tree
|
|
44
|
-
* view, hook-threaded nested reads) throw
|
|
45
|
-
* 'ReadContext cannot be reused across request authorities'.
|
|
46
|
-
* - The refresh path rotates the refresh token; a second unmemoized call
|
|
47
|
-
* in the same request would re-run the dance against the
|
|
48
|
-
* already-rotated cookie and sign the admin out.
|
|
49
|
-
*/
|
|
50
|
-
|
|
51
|
-
import { ERR_UNAUTHENTICATED, type RequestContext } from '@byline/auth'
|
|
52
|
-
import { getServerConfig } from '@byline/core'
|
|
53
|
-
import { v7 as uuidv7 } from 'uuid'
|
|
54
|
-
|
|
55
|
-
import {
|
|
56
|
-
clearSessionCookies,
|
|
57
|
-
readAccessTokenCookie,
|
|
58
|
-
readRefreshTokenCookie,
|
|
59
|
-
setSessionCookies,
|
|
60
|
-
} from './auth-cookies.js'
|
|
61
|
-
import { oncePerRequest } from './request-scope.js'
|
|
62
|
-
|
|
63
|
-
function requireSessionProvider() {
|
|
64
|
-
const provider = getServerConfig().sessionProvider
|
|
65
|
-
if (!provider) {
|
|
66
|
-
throw new Error(
|
|
67
|
-
'No sessionProvider configured on ServerConfig. ' +
|
|
68
|
-
'Construct a JwtSessionProvider in your server config and pass it to initBylineCore().'
|
|
69
|
-
)
|
|
70
|
-
}
|
|
71
|
-
return provider
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
export async function getAdminRequestContext(): Promise<RequestContext> {
|
|
75
|
-
return oncePerRequest('byline:admin-request-context', resolveAdminRequestContext)
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
async function resolveAdminRequestContext(): Promise<RequestContext> {
|
|
79
|
-
const provider = requireSessionProvider()
|
|
80
|
-
|
|
81
|
-
const accessToken = readAccessTokenCookie()
|
|
82
|
-
|
|
83
|
-
// Happy path: valid access token.
|
|
84
|
-
if (accessToken) {
|
|
85
|
-
try {
|
|
86
|
-
const { actor } = await provider.verifyAccessToken(accessToken)
|
|
87
|
-
return {
|
|
88
|
-
actor,
|
|
89
|
-
requestId: uuidv7(),
|
|
90
|
-
readMode: 'any',
|
|
91
|
-
}
|
|
92
|
-
} catch {
|
|
93
|
-
// Fall through to refresh — we'll burn a rotation only when the
|
|
94
|
-
// access token genuinely can't verify.
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
// Refresh path: swap the refresh cookie for a fresh token pair.
|
|
99
|
-
const refreshToken = readRefreshTokenCookie()
|
|
100
|
-
if (!refreshToken) {
|
|
101
|
-
// Only emit cookie clears when the browser actually sent a stale access
|
|
102
|
-
// cookie — otherwise the response carries no Set-Cookie at all, which
|
|
103
|
-
// lets shared caches (Cloudflare) cache public pages for anonymous
|
|
104
|
-
// visitors. Set-Cookie on the response is a hard bypass signal for CDNs.
|
|
105
|
-
if (accessToken) {
|
|
106
|
-
clearSessionCookies()
|
|
107
|
-
}
|
|
108
|
-
throw ERR_UNAUTHENTICATED({ message: 'no admin session' })
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
let refreshed: Awaited<ReturnType<typeof provider.refreshSession>>
|
|
112
|
-
try {
|
|
113
|
-
refreshed = await provider.refreshSession({ refreshToken })
|
|
114
|
-
} catch (err) {
|
|
115
|
-
clearSessionCookies()
|
|
116
|
-
throw ERR_UNAUTHENTICATED({
|
|
117
|
-
message: 'admin session could not be refreshed',
|
|
118
|
-
cause: err,
|
|
119
|
-
})
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
// Write the new cookies so subsequent requests skip the refresh path.
|
|
123
|
-
setSessionCookies(refreshed)
|
|
124
|
-
|
|
125
|
-
// Verify the freshly-minted access token to extract the actor.
|
|
126
|
-
let verified: Awaited<ReturnType<typeof provider.verifyAccessToken>>
|
|
127
|
-
try {
|
|
128
|
-
verified = await provider.verifyAccessToken(refreshed.accessToken)
|
|
129
|
-
} catch (err) {
|
|
130
|
-
clearSessionCookies()
|
|
131
|
-
throw ERR_UNAUTHENTICATED({
|
|
132
|
-
message: 'refreshed access token did not verify',
|
|
133
|
-
cause: err,
|
|
134
|
-
})
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
return {
|
|
138
|
-
actor: verified.actor,
|
|
139
|
-
requestId: uuidv7(),
|
|
140
|
-
readMode: 'any',
|
|
141
|
-
}
|
|
142
|
-
}
|
package/src/auth/auth-cookies.ts
DELETED
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* This Source Code is subject to the terms of the Mozilla Public
|
|
3
|
-
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
4
|
-
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
5
|
-
*
|
|
6
|
-
* Copyright (c) Infonomic Company Limited
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Cookie helpers for admin session management.
|
|
11
|
-
*
|
|
12
|
-
* Two separate httpOnly cookies, one for each token half:
|
|
13
|
-
*
|
|
14
|
-
* - `byline_access_token` — short-lived JWT; sent on every request.
|
|
15
|
-
* - `byline_refresh_token` — long-lived opaque string; sent back only
|
|
16
|
-
* when the access cookie is missing or
|
|
17
|
-
* expired, to mint a new access token.
|
|
18
|
-
*
|
|
19
|
-
* Presenting "one session" to the user is a function of the middleware —
|
|
20
|
-
* `getAdminRequestContext()` transparently refreshes the access cookie
|
|
21
|
-
* using the refresh cookie, so the UI layer doesn't have to care.
|
|
22
|
-
*
|
|
23
|
-
* All cookies set here use:
|
|
24
|
-
* - `httpOnly: true` — inaccessible to JavaScript (XSS-hardened).
|
|
25
|
-
* - `sameSite: 'lax'` — sent on top-level navigations but not
|
|
26
|
-
* cross-origin subrequests (reasonable default
|
|
27
|
-
* for an admin SSR app).
|
|
28
|
-
* - `secure: true` in production — https-only; dev keeps it off so
|
|
29
|
-
* cookies work on http://localhost.
|
|
30
|
-
* - `path: '/'` — available everywhere in the app.
|
|
31
|
-
*/
|
|
32
|
-
|
|
33
|
-
import { getCookie, setCookie } from '@tanstack/react-start/server'
|
|
34
|
-
|
|
35
|
-
export const ACCESS_TOKEN_COOKIE = 'byline_access_token'
|
|
36
|
-
export const REFRESH_TOKEN_COOKIE = 'byline_refresh_token'
|
|
37
|
-
|
|
38
|
-
const IS_PROD = process.env.NODE_ENV === 'production'
|
|
39
|
-
|
|
40
|
-
/** Read the access-token cookie. Returns undefined when not present. */
|
|
41
|
-
export function readAccessTokenCookie(): string | undefined {
|
|
42
|
-
return getCookie(ACCESS_TOKEN_COOKIE)
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/** Read the refresh-token cookie. Returns undefined when not present. */
|
|
46
|
-
export function readRefreshTokenCookie(): string | undefined {
|
|
47
|
-
return getCookie(REFRESH_TOKEN_COOKIE)
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export interface SessionCookieTokens {
|
|
51
|
-
accessToken: string
|
|
52
|
-
refreshToken: string
|
|
53
|
-
accessTokenExpiresAt: Date
|
|
54
|
-
refreshTokenExpiresAt: Date
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Write both access and refresh cookies. Called after sign-in and after
|
|
59
|
-
* every transparent refresh in `getAdminRequestContext()`.
|
|
60
|
-
*
|
|
61
|
-
* `maxAge` is derived from each token's own expiry claim so the browser
|
|
62
|
-
* drops the cookies at the same moment the server would reject them —
|
|
63
|
-
* saves round trips when the refresh token has fully expired.
|
|
64
|
-
*/
|
|
65
|
-
export function setSessionCookies(tokens: SessionCookieTokens): void {
|
|
66
|
-
const now = Date.now()
|
|
67
|
-
const accessMaxAgeSeconds = Math.max(
|
|
68
|
-
0,
|
|
69
|
-
Math.floor((tokens.accessTokenExpiresAt.getTime() - now) / 1000)
|
|
70
|
-
)
|
|
71
|
-
const refreshMaxAgeSeconds = Math.max(
|
|
72
|
-
0,
|
|
73
|
-
Math.floor((tokens.refreshTokenExpiresAt.getTime() - now) / 1000)
|
|
74
|
-
)
|
|
75
|
-
|
|
76
|
-
setCookie(ACCESS_TOKEN_COOKIE, tokens.accessToken, {
|
|
77
|
-
httpOnly: true,
|
|
78
|
-
sameSite: 'lax',
|
|
79
|
-
secure: IS_PROD,
|
|
80
|
-
path: '/',
|
|
81
|
-
maxAge: accessMaxAgeSeconds,
|
|
82
|
-
})
|
|
83
|
-
|
|
84
|
-
setCookie(REFRESH_TOKEN_COOKIE, tokens.refreshToken, {
|
|
85
|
-
httpOnly: true,
|
|
86
|
-
sameSite: 'lax',
|
|
87
|
-
secure: IS_PROD,
|
|
88
|
-
path: '/',
|
|
89
|
-
maxAge: refreshMaxAgeSeconds,
|
|
90
|
-
})
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* Clear both session cookies. Called on sign-out and on any auth failure
|
|
95
|
-
* during `getAdminRequestContext()` (ensures the browser does not keep
|
|
96
|
-
* trying a token that the server has already rejected).
|
|
97
|
-
*/
|
|
98
|
-
export function clearSessionCookies(): void {
|
|
99
|
-
setCookie(ACCESS_TOKEN_COOKIE, '', {
|
|
100
|
-
httpOnly: true,
|
|
101
|
-
sameSite: 'lax',
|
|
102
|
-
secure: IS_PROD,
|
|
103
|
-
path: '/',
|
|
104
|
-
maxAge: 0,
|
|
105
|
-
})
|
|
106
|
-
setCookie(REFRESH_TOKEN_COOKIE, '', {
|
|
107
|
-
httpOnly: true,
|
|
108
|
-
sameSite: 'lax',
|
|
109
|
-
secure: IS_PROD,
|
|
110
|
-
path: '/',
|
|
111
|
-
maxAge: 0,
|
|
112
|
-
})
|
|
113
|
-
}
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* This Source Code is subject to the terms of the Mozilla Public
|
|
3
|
-
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
4
|
-
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
|
5
|
-
*
|
|
6
|
-
* Copyright (c) Infonomic Company Limited
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* Cookie helpers for the front-end *preview mode* toggle.
|
|
11
|
-
*
|
|
12
|
-
* Preview mode lets a signed-in admin see draft (and other non-published)
|
|
13
|
-
* versions on the public host pages without changing any markup or route
|
|
14
|
-
* structure. The mechanic is intentionally narrow:
|
|
15
|
-
*
|
|
16
|
-
* - A single httpOnly cookie (`byline_preview=1`) carries the user's
|
|
17
|
-
* "show me drafts" intent across requests within the same browser
|
|
18
|
-
* session.
|
|
19
|
-
* - The cookie's mere *presence* is the signal — there is no payload to
|
|
20
|
-
* verify. The actual safety check is the admin session: when the
|
|
21
|
-
* viewer client (or a server fn) sees the cookie, it tries to resolve
|
|
22
|
-
* `getAdminRequestContext()` and only elevates the read mode when a
|
|
23
|
-
* valid admin session resolves. A stale preview cookie on an
|
|
24
|
-
* anonymous browser falls through to public/published reads silently.
|
|
25
|
-
*
|
|
26
|
-
* Cookie attributes:
|
|
27
|
-
* - `httpOnly: true` — inaccessible to JS; toggled only via server fns.
|
|
28
|
-
* - `sameSite: 'lax'` — sent on top-level navigations only.
|
|
29
|
-
* - `secure: true` in production — https-only.
|
|
30
|
-
* - `path: '/'` — visible to every public route.
|
|
31
|
-
* - `maxAge: 1 day` — preview is meant to be a short-lived editorial
|
|
32
|
-
* mode, not a permanent state. Admins can
|
|
33
|
-
* re-enable from the admin UI when needed.
|
|
34
|
-
*/
|
|
35
|
-
|
|
36
|
-
import { getCookie, setCookie } from '@tanstack/react-start/server'
|
|
37
|
-
|
|
38
|
-
export const PREVIEW_COOKIE = 'byline_preview'
|
|
39
|
-
const PREVIEW_MAX_AGE_SECONDS = 60 * 60 * 24 // 1 day
|
|
40
|
-
|
|
41
|
-
const IS_PROD = process.env.NODE_ENV === 'production'
|
|
42
|
-
|
|
43
|
-
/** True iff the preview cookie is currently set on the request. */
|
|
44
|
-
export function readPreviewCookie(): boolean {
|
|
45
|
-
return getCookie(PREVIEW_COOKIE) === '1'
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Write the preview cookie. Callers should ensure the request is from a
|
|
50
|
-
* valid admin session before invoking — the cookie itself is just a flag
|
|
51
|
-
* and carries no proof of authorisation. See `enablePreviewModeFn` for
|
|
52
|
-
* the canonical entry point.
|
|
53
|
-
*/
|
|
54
|
-
export function setPreviewCookie(): void {
|
|
55
|
-
setCookie(PREVIEW_COOKIE, '1', {
|
|
56
|
-
httpOnly: true,
|
|
57
|
-
sameSite: 'lax',
|
|
58
|
-
secure: IS_PROD,
|
|
59
|
-
path: '/',
|
|
60
|
-
maxAge: PREVIEW_MAX_AGE_SECONDS,
|
|
61
|
-
})
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/** Clear the preview cookie. Safe to call from any context. */
|
|
65
|
-
export function clearPreviewCookie(): void {
|
|
66
|
-
setCookie(PREVIEW_COOKIE, '', {
|
|
67
|
-
httpOnly: true,
|
|
68
|
-
sameSite: 'lax',
|
|
69
|
-
secure: IS_PROD,
|
|
70
|
-
path: '/',
|
|
71
|
-
maxAge: 0,
|
|
72
|
-
})
|
|
73
|
-
}
|