@memberjunction/server 5.50.0 → 5.51.1
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/agentSessions/SessionManager.d.ts.map +1 -1
- package/dist/agentSessions/SessionManager.js +6 -1
- package/dist/agentSessions/SessionManager.js.map +1 -1
- package/dist/auth/index.d.ts +8 -0
- package/dist/auth/index.d.ts.map +1 -1
- package/dist/auth/index.js +53 -13
- package/dist/auth/index.js.map +1 -1
- package/dist/config.d.ts +24 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +12 -0
- package/dist/config.js.map +1 -1
- package/dist/context.d.ts.map +1 -1
- package/dist/context.js +19 -2
- package/dist/context.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/realtimeWidget/widgetGuestElevation.d.ts +22 -0
- package/dist/realtimeWidget/widgetGuestElevation.d.ts.map +1 -1
- package/dist/realtimeWidget/widgetGuestElevation.js +36 -0
- package/dist/realtimeWidget/widgetGuestElevation.js.map +1 -1
- package/dist/resolvers/RealtimeClientSessionResolver.d.ts +21 -0
- package/dist/resolvers/RealtimeClientSessionResolver.d.ts.map +1 -1
- package/dist/resolvers/RealtimeClientSessionResolver.js +75 -16
- package/dist/resolvers/RealtimeClientSessionResolver.js.map +1 -1
- package/dist/resolvers/ReportResolver.d.ts.map +1 -1
- package/dist/resolvers/ReportResolver.js +2 -1
- package/dist/resolvers/ReportResolver.js.map +1 -1
- package/dist/rest/OAuthCallbackHandler.d.ts +49 -1
- package/dist/rest/OAuthCallbackHandler.d.ts.map +1 -1
- package/dist/rest/OAuthCallbackHandler.js +129 -43
- package/dist/rest/OAuthCallbackHandler.js.map +1 -1
- package/package.json +89 -89
- package/src/__tests__/OAuthCallbackHandler.openRedirect.test.ts +117 -0
- package/src/__tests__/OAuthCallbackHandler.xss.test.ts +4 -1
- package/src/__tests__/RealtimeClientSessionResolver.test.ts +420 -0
- package/src/__tests__/SessionManager.test.ts +62 -0
- package/src/__tests__/newUsers.test.ts +729 -0
- package/src/__tests__/widgetGuestElevation.test.ts +70 -2
- package/src/agentSessions/SessionManager.ts +6 -1
- package/src/auth/index.ts +56 -15
- package/src/config.ts +12 -0
- package/src/context.ts +19 -2
- package/src/index.ts +3 -1
- package/src/realtimeWidget/widgetGuestElevation.ts +41 -0
- package/src/resolvers/RealtimeClientSessionResolver.ts +84 -16
- package/src/resolvers/ReportResolver.ts +2 -1
- package/src/resolvers/__tests__/ReportResolver.test.ts +232 -0
- package/src/rest/OAuthCallbackHandler.ts +149 -41
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for ReportResolverExtended.CreateReportFromConversationDetailID.
|
|
3
|
+
*
|
|
4
|
+
* Regression coverage for a SQL injection fix: ConversationDetailID (a plain GraphQL
|
|
5
|
+
* String arg) used to be interpolated directly into the WHERE clause. It is now bound
|
|
6
|
+
* via mssql's parameterized `request.input(...)`, so a hostile value must never appear
|
|
7
|
+
* spliced into the executed SQL text, and query structure must stay identical regardless
|
|
8
|
+
* of what the value contains.
|
|
9
|
+
*/
|
|
10
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
11
|
+
|
|
12
|
+
// ─── Hoisted mocks ────────────────────────────────────────────────────────
|
|
13
|
+
const { mockUserCacheUsers, mssqlState } = vi.hoisted(() => ({
|
|
14
|
+
mockUserCacheUsers: [] as Array<{ Email: string; ID: string }>,
|
|
15
|
+
mssqlState: {
|
|
16
|
+
inputCalls: [] as Array<{ name: string; type: unknown; value: unknown }>,
|
|
17
|
+
queryCalls: [] as string[],
|
|
18
|
+
poolArgs: [] as unknown[],
|
|
19
|
+
recordset: [] as Array<Record<string, unknown>>,
|
|
20
|
+
},
|
|
21
|
+
}));
|
|
22
|
+
|
|
23
|
+
// Stub external deps before imports (mirrors resolverBase.rls.test.ts)
|
|
24
|
+
vi.mock('@memberjunction/sqlserver-dataprovider', () => ({
|
|
25
|
+
SQLServerDataProvider: class {},
|
|
26
|
+
UserCache: {
|
|
27
|
+
get Users() { return mockUserCacheUsers; },
|
|
28
|
+
},
|
|
29
|
+
}));
|
|
30
|
+
|
|
31
|
+
vi.mock('cloudevents', () => ({
|
|
32
|
+
CloudEvent: class {},
|
|
33
|
+
httpTransport: () => () => undefined,
|
|
34
|
+
emitterFor: () => () => undefined,
|
|
35
|
+
}));
|
|
36
|
+
|
|
37
|
+
vi.mock('type-graphql', () => ({
|
|
38
|
+
Resolver: () => () => undefined,
|
|
39
|
+
Mutation: () => () => undefined,
|
|
40
|
+
Query: () => () => undefined,
|
|
41
|
+
Subscription: () => () => undefined,
|
|
42
|
+
Ctx: () => () => undefined,
|
|
43
|
+
Arg: () => () => undefined,
|
|
44
|
+
PubSub: () => () => undefined,
|
|
45
|
+
Root: () => () => undefined,
|
|
46
|
+
ObjectType: () => () => undefined,
|
|
47
|
+
InputType: () => () => undefined,
|
|
48
|
+
Field: () => () => undefined,
|
|
49
|
+
FieldResolver: () => () => undefined,
|
|
50
|
+
Int: () => undefined,
|
|
51
|
+
Float: () => undefined,
|
|
52
|
+
registerEnumType: () => undefined,
|
|
53
|
+
}));
|
|
54
|
+
|
|
55
|
+
vi.mock('graphql', () => ({
|
|
56
|
+
GraphQLError: class extends Error {
|
|
57
|
+
constructor(msg: string) { super(msg); }
|
|
58
|
+
},
|
|
59
|
+
}));
|
|
60
|
+
|
|
61
|
+
vi.mock('mssql', () => {
|
|
62
|
+
const UniqueIdentifier = { __marker: 'UniqueIdentifier' };
|
|
63
|
+
class Request {
|
|
64
|
+
constructor(pool: unknown) {
|
|
65
|
+
mssqlState.poolArgs.push(pool);
|
|
66
|
+
}
|
|
67
|
+
input(name: string, type: unknown, value: unknown) {
|
|
68
|
+
mssqlState.inputCalls.push({ name, type, value });
|
|
69
|
+
}
|
|
70
|
+
async query(sql: string) {
|
|
71
|
+
mssqlState.queryCalls.push(sql);
|
|
72
|
+
return { recordset: mssqlState.recordset };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { default: { Request, UniqueIdentifier }, Request, UniqueIdentifier };
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
vi.mock('@memberjunction/data-context', () => {
|
|
79
|
+
class DataContext {
|
|
80
|
+
LoadMetadata = vi.fn(async () => true);
|
|
81
|
+
}
|
|
82
|
+
(DataContext as unknown as { Clone: unknown }).Clone = vi.fn(async () => ({ ID: 'dctx-clone-1' }));
|
|
83
|
+
return { DataContext };
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
vi.mock('@memberjunction/api-keys', () => ({
|
|
87
|
+
GetAPIKeyEngine: vi.fn(),
|
|
88
|
+
}));
|
|
89
|
+
|
|
90
|
+
vi.mock('@memberjunction/encryption', () => ({
|
|
91
|
+
EncryptionEngine: { Instance: {} },
|
|
92
|
+
}));
|
|
93
|
+
|
|
94
|
+
vi.mock('@memberjunction/graphql-dataprovider', () => ({
|
|
95
|
+
FieldMapper: class { static Instance = { MapFieldsFromCodeNamesToDBNames: vi.fn() }; },
|
|
96
|
+
}));
|
|
97
|
+
|
|
98
|
+
vi.mock('../../generic/PubSubManager.js', () => ({
|
|
99
|
+
PubSubManager: class { static Instance = { publish: vi.fn() }; },
|
|
100
|
+
}));
|
|
101
|
+
|
|
102
|
+
vi.mock('../../generic/PushStatusResolver.js', () => ({
|
|
103
|
+
PUSH_STATUS_UPDATES_TOPIC: 'test-push-topic',
|
|
104
|
+
PushStatusNotification: class {},
|
|
105
|
+
PushStatusResolver: class {},
|
|
106
|
+
}));
|
|
107
|
+
|
|
108
|
+
vi.mock('../../generic/CacheInvalidationResolver.js', () => ({
|
|
109
|
+
CACHE_INVALIDATION_TOPIC: 'test-cache-topic',
|
|
110
|
+
}));
|
|
111
|
+
|
|
112
|
+
vi.mock('../../generic/RunViewResolver.js', () => ({
|
|
113
|
+
RunViewByIDInput: class {},
|
|
114
|
+
RunViewByNameInput: class {},
|
|
115
|
+
RunDynamicViewInput: class {},
|
|
116
|
+
}));
|
|
117
|
+
|
|
118
|
+
vi.mock('../../generic/DeleteOptionsInput.js', () => ({
|
|
119
|
+
DeleteOptionsInput: class {},
|
|
120
|
+
}));
|
|
121
|
+
|
|
122
|
+
vi.mock('../../types.js', () => ({
|
|
123
|
+
RunViewGenericParams: class {},
|
|
124
|
+
}));
|
|
125
|
+
|
|
126
|
+
vi.mock('@memberjunction/core', async () => {
|
|
127
|
+
const actual = await vi.importActual<typeof import('@memberjunction/core')>('@memberjunction/core');
|
|
128
|
+
return {
|
|
129
|
+
...actual,
|
|
130
|
+
LogError: vi.fn(),
|
|
131
|
+
LogStatus: vi.fn(),
|
|
132
|
+
};
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
vi.mock('@memberjunction/core-entities', () => ({}));
|
|
136
|
+
|
|
137
|
+
// ─── Import after mocks ──────────────────────────────────────────────────
|
|
138
|
+
import { ReportResolverExtended } from '../ReportResolver';
|
|
139
|
+
|
|
140
|
+
// ─── Helpers ──────────────────────────────────────────────────────────────
|
|
141
|
+
|
|
142
|
+
function makeReportEntity() {
|
|
143
|
+
return {
|
|
144
|
+
ID: 'report-1',
|
|
145
|
+
Name: '',
|
|
146
|
+
Description: '',
|
|
147
|
+
ConversationID: '',
|
|
148
|
+
ConversationDetailID: '',
|
|
149
|
+
DataContextID: '',
|
|
150
|
+
Configuration: '',
|
|
151
|
+
SharingScope: '',
|
|
152
|
+
UserID: '',
|
|
153
|
+
NewRecord: vi.fn(),
|
|
154
|
+
Save: vi.fn(async () => true),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function makeContext(getEntityObject: () => ReturnType<typeof makeReportEntity>) {
|
|
159
|
+
const md = {
|
|
160
|
+
Entities: [
|
|
161
|
+
{ Name: 'MJ: Conversation Details', SchemaName: 'dbo', BaseView: 'vwConversationDetails' },
|
|
162
|
+
{ Name: 'MJ: Conversations', SchemaName: 'dbo', BaseView: 'vwConversations' },
|
|
163
|
+
],
|
|
164
|
+
GetEntityObject: vi.fn(async () => getEntityObject()),
|
|
165
|
+
};
|
|
166
|
+
return {
|
|
167
|
+
dataSource: { __fakePool: true },
|
|
168
|
+
userPayload: { email: 'test@example.com' }, // no apiKeyHash -> scope check no-ops
|
|
169
|
+
providers: [{ type: 'Read-Write', provider: md }],
|
|
170
|
+
} as unknown as Parameters<ReportResolverExtended['CreateReportFromConversationDetailID']>[1];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
describe('ReportResolverExtended.CreateReportFromConversationDetailID', () => {
|
|
174
|
+
let resolver: ReportResolverExtended;
|
|
175
|
+
|
|
176
|
+
beforeEach(() => {
|
|
177
|
+
resolver = new ReportResolverExtended();
|
|
178
|
+
mssqlState.inputCalls.length = 0;
|
|
179
|
+
mssqlState.queryCalls.length = 0;
|
|
180
|
+
mssqlState.poolArgs.length = 0;
|
|
181
|
+
mssqlState.recordset.length = 0;
|
|
182
|
+
mssqlState.recordset.push({
|
|
183
|
+
Message: JSON.stringify({ title: 'Test Report', userExplanation: 'exp' }),
|
|
184
|
+
ConversationID: 'conv-1',
|
|
185
|
+
DataContextID: 'dctx-1',
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
mockUserCacheUsers.length = 0;
|
|
189
|
+
mockUserCacheUsers.push({ Email: 'test@example.com', ID: 'user-1' });
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it('binds ConversationDetailID as a query parameter rather than splicing it into the SQL text', async () => {
|
|
193
|
+
const maliciousID = "1'; DROP TABLE MJ_Reports; --";
|
|
194
|
+
const context = makeContext(makeReportEntity);
|
|
195
|
+
|
|
196
|
+
const result = await resolver.CreateReportFromConversationDetailID(maliciousID, context);
|
|
197
|
+
|
|
198
|
+
expect(result.Success).toBe(true);
|
|
199
|
+
|
|
200
|
+
// The query text must use a bound parameter, never the raw value.
|
|
201
|
+
expect(mssqlState.queryCalls).toHaveLength(1);
|
|
202
|
+
expect(mssqlState.queryCalls[0]).toContain('@ConversationDetailID');
|
|
203
|
+
expect(mssqlState.queryCalls[0]).not.toContain(maliciousID);
|
|
204
|
+
expect(mssqlState.queryCalls[0]).not.toContain('DROP TABLE');
|
|
205
|
+
|
|
206
|
+
// The value must be bound through request.input, not string concatenation.
|
|
207
|
+
expect(mssqlState.inputCalls).toHaveLength(1);
|
|
208
|
+
expect(mssqlState.inputCalls[0].name).toBe('ConversationDetailID');
|
|
209
|
+
expect(mssqlState.inputCalls[0].value).toBe(maliciousID);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it('does not alter query structure for values containing quotes, --, or OR 1=1', async () => {
|
|
213
|
+
const hostileID = "abc' OR '1'='1' --";
|
|
214
|
+
const context = makeContext(makeReportEntity);
|
|
215
|
+
|
|
216
|
+
await resolver.CreateReportFromConversationDetailID(hostileID, context);
|
|
217
|
+
|
|
218
|
+
expect(mssqlState.queryCalls[0]).toMatch(/WHERE\s+cd\.ID=@ConversationDetailID\s*$/);
|
|
219
|
+
expect(mssqlState.inputCalls[0].value).toBe(hostileID);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it('still succeeds end to end for a normal GUID-shaped value', async () => {
|
|
223
|
+
const normalID = '12345678-1234-1234-1234-123456789012';
|
|
224
|
+
const context = makeContext(makeReportEntity);
|
|
225
|
+
|
|
226
|
+
const result = await resolver.CreateReportFromConversationDetailID(normalID, context);
|
|
227
|
+
|
|
228
|
+
expect(result.Success).toBe(true);
|
|
229
|
+
expect(result.ReportName).toBe('Test Report');
|
|
230
|
+
expect(mssqlState.inputCalls[0].value).toBe(normalID);
|
|
231
|
+
});
|
|
232
|
+
});
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
|
|
15
15
|
import express from 'express';
|
|
16
16
|
import { LogError, LogStatus, RunView, UserInfo } from '@memberjunction/core';
|
|
17
|
-
import { UUIDsEqual } from '@memberjunction/global';
|
|
17
|
+
import { IsValidUUID, UUIDsEqual } from '@memberjunction/global';
|
|
18
18
|
import { UserCache } from '@memberjunction/sqlserver-dataprovider';
|
|
19
19
|
import { OAuthManager, MCPClientManager } from '@memberjunction/ai-mcp-client';
|
|
20
20
|
import type { MCPServerOAuthConfig } from '@memberjunction/ai-mcp-client';
|
|
@@ -38,6 +38,23 @@ export interface OAuthCallbackHandlerOptions {
|
|
|
38
38
|
successRedirectUrl?: string;
|
|
39
39
|
/** URL to redirect to after failed authorization */
|
|
40
40
|
errorRedirectUrl?: string;
|
|
41
|
+
/**
|
|
42
|
+
* Origins a caller-supplied `frontendReturnUrl` is allowed to point at, so the OAuth callback
|
|
43
|
+
* cannot be turned into an open redirect from the trusted MJAPI origin. Normally wired to
|
|
44
|
+
* `cors.allowedOrigins`. Pass `['*']` to allow any origin — MJ's backward-compatible default
|
|
45
|
+
* CORS posture, and what a deployment that has not narrowed `cors.allowedOrigins` gets.
|
|
46
|
+
*
|
|
47
|
+
* REQUIRED on purpose. An optional field defaulting to allow-all is fail-open: a construction
|
|
48
|
+
* site that forgets it loses the open-redirect protection silently, with nothing to notice.
|
|
49
|
+
* Being required makes that a compile error instead. The handler is not exported from this
|
|
50
|
+
* package's barrel and the package declares no subpath exports, so no consumer outside MJServer
|
|
51
|
+
* can construct it — revisit this if it is ever added to the public API.
|
|
52
|
+
*
|
|
53
|
+
* Injected rather than read from `configInfo` directly so this module has no import-time
|
|
54
|
+
* dependency on configuration loading — importing the config module validates the whole config
|
|
55
|
+
* as a side effect, which makes this handler unimportable in any context without one.
|
|
56
|
+
*/
|
|
57
|
+
allowedFrontendOrigins: string[];
|
|
41
58
|
}
|
|
42
59
|
|
|
43
60
|
/**
|
|
@@ -46,10 +63,15 @@ export interface OAuthCallbackHandlerOptions {
|
|
|
46
63
|
* The callback endpoint is unauthenticated because it's called by external auth servers.
|
|
47
64
|
* It uses the state parameter to look up the authorization context and validate the flow.
|
|
48
65
|
*
|
|
66
|
+
* NOTE: `allowedFrontendOrigins` is what prevents the callback becoming an open redirect, and is
|
|
67
|
+
* required so it cannot be forgotten. Wire it to `configInfo.cors?.allowedOrigins`; `['*']` allows
|
|
68
|
+
* any origin, matching MJ's default CORS posture.
|
|
69
|
+
*
|
|
49
70
|
* @example
|
|
50
71
|
* ```typescript
|
|
51
72
|
* const oauthHandler = new OAuthCallbackHandler({
|
|
52
|
-
* publicUrl: 'https://api.example.com'
|
|
73
|
+
* publicUrl: 'https://api.example.com',
|
|
74
|
+
* allowedFrontendOrigins: configInfo.cors?.allowedOrigins ?? ['*']
|
|
53
75
|
* });
|
|
54
76
|
*
|
|
55
77
|
* // Mount unauthenticated callback route
|
|
@@ -348,7 +370,10 @@ export class OAuthCallbackHandler {
|
|
|
348
370
|
* @param res - Express response
|
|
349
371
|
*/
|
|
350
372
|
private async initiateFlow(req: express.Request, res: express.Response): Promise<void> {
|
|
351
|
-
|
|
373
|
+
// Coerce request-body values to strings up front. A JSON body can carry arrays/objects, and
|
|
374
|
+
// passing those downstream unvalidated turns a bad request into a confusing internal failure.
|
|
375
|
+
const connectionId: string = typeof req.body?.connectionId === 'string' ? req.body.connectionId : '';
|
|
376
|
+
const { additionalScopes, frontendReturnUrl } = req.body;
|
|
352
377
|
const contextUser = req['mjUser'] as UserInfo;
|
|
353
378
|
|
|
354
379
|
if (!contextUser) {
|
|
@@ -368,6 +393,29 @@ export class OAuthCallbackHandler {
|
|
|
368
393
|
return;
|
|
369
394
|
}
|
|
370
395
|
|
|
396
|
+
// connectionId is a record ID (UUID). Reject anything else at the boundary so it can never
|
|
397
|
+
// reach a SQL filter or downstream consumer as injectable input.
|
|
398
|
+
if (!IsValidUUID(connectionId)) {
|
|
399
|
+
res.status(400).json({
|
|
400
|
+
success: false,
|
|
401
|
+
errorCode: 'invalid_request',
|
|
402
|
+
errorMessage: 'connectionId must be a valid record identifier'
|
|
403
|
+
});
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// Reject a disallowed return URL here rather than at the callback. Otherwise the caller only
|
|
408
|
+
// finds out after the whole OAuth round trip, by being silently sent to the default page.
|
|
409
|
+
// An absent value is acceptable — see isFrontendReturnUrlAcceptable.
|
|
410
|
+
if (!this.isFrontendReturnUrlAcceptable(frontendReturnUrl)) {
|
|
411
|
+
res.status(400).json({
|
|
412
|
+
success: false,
|
|
413
|
+
errorCode: 'invalid_request',
|
|
414
|
+
errorMessage: 'frontendReturnUrl is not an allowed redirect target'
|
|
415
|
+
});
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
|
|
371
419
|
try {
|
|
372
420
|
// Load connection and server config
|
|
373
421
|
const config = await this.loadConnectionConfig(connectionId, contextUser);
|
|
@@ -644,10 +692,13 @@ export class OAuthCallbackHandler {
|
|
|
644
692
|
try {
|
|
645
693
|
const rv = new RunView();
|
|
646
694
|
|
|
647
|
-
// Get connection to get server ID
|
|
695
|
+
// Get connection to get server ID.
|
|
696
|
+
// connectionId is caller-supplied (POST /oauth/initiate body). MJ ExtraFilter is a raw
|
|
697
|
+
// SQL fragment, so single quotes MUST be doubled to prevent injection — matching the
|
|
698
|
+
// escaping used for stateParameter in loadAuthorizationState().
|
|
648
699
|
const connResult = await rv.RunView<{ MCPServerID: string }>({
|
|
649
700
|
EntityName: ENTITY_MCP_SERVER_CONNECTIONS,
|
|
650
|
-
ExtraFilter: `ID='${connectionId}'`,
|
|
701
|
+
ExtraFilter: `ID='${connectionId.replace(/'/g, "''")}'`,
|
|
651
702
|
Fields: ['MCPServerID'],
|
|
652
703
|
ResultType: 'simple'
|
|
653
704
|
}, contextUser);
|
|
@@ -696,32 +747,93 @@ export class OAuthCallbackHandler {
|
|
|
696
747
|
}
|
|
697
748
|
}
|
|
698
749
|
|
|
750
|
+
/**
|
|
751
|
+
* Validates that a caller-supplied frontend return URL points at an allowed origin, so the
|
|
752
|
+
* OAuth callback cannot be turned into an open redirect from the trusted MJAPI origin.
|
|
753
|
+
*
|
|
754
|
+
* Allowed when: the allowlist is "allow all" (`['*']`, the backward-compatible default),
|
|
755
|
+
* the URL's origin is in `options.allowedFrontendOrigins`, or it matches the origin of a
|
|
756
|
+
* built-in success/error redirect URL. Anything else is rejected and the caller falls back to
|
|
757
|
+
* the default redirect page.
|
|
758
|
+
*/
|
|
759
|
+
private isFrontendReturnUrlAllowed(url: URL): boolean {
|
|
760
|
+
const allowed = this.options.allowedFrontendOrigins;
|
|
761
|
+
if (allowed.includes('*')) {
|
|
762
|
+
return true;
|
|
763
|
+
}
|
|
764
|
+
if (allowed.includes(url.origin)) {
|
|
765
|
+
return true;
|
|
766
|
+
}
|
|
767
|
+
for (const builtIn of [this.options.successRedirectUrl, this.options.errorRedirectUrl]) {
|
|
768
|
+
try {
|
|
769
|
+
if (builtIn && new URL(builtIn).origin === url.origin) {
|
|
770
|
+
return true;
|
|
771
|
+
}
|
|
772
|
+
} catch {
|
|
773
|
+
// Ignore an unparseable built-in URL and keep checking.
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
return false;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* Parses a caller-supplied return URL and applies {@link isFrontendReturnUrlAllowed}.
|
|
781
|
+
*
|
|
782
|
+
* @returns the parsed URL when it is well-formed AND points at an allowed origin, otherwise null.
|
|
783
|
+
*/
|
|
784
|
+
private parseAllowedFrontendReturnUrl(frontendReturnUrl: string): URL | null {
|
|
785
|
+
let url: URL;
|
|
786
|
+
try {
|
|
787
|
+
url = new URL(frontendReturnUrl);
|
|
788
|
+
} catch {
|
|
789
|
+
LogError(`[OAuth Callback] Invalid frontend return URL '${frontendReturnUrl}', falling back to default`);
|
|
790
|
+
return null;
|
|
791
|
+
}
|
|
792
|
+
if (!this.isFrontendReturnUrlAllowed(url)) {
|
|
793
|
+
LogError(`[OAuth Callback] frontend return URL '${frontendReturnUrl}' origin not allowed, falling back to default`);
|
|
794
|
+
return null;
|
|
795
|
+
}
|
|
796
|
+
return url;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/**
|
|
800
|
+
* Boundary check for `/oauth/initiate` — validates the return URL before it is persisted onto
|
|
801
|
+
* the authorization state, so a caller gets a 400 instead of a silent fallback later.
|
|
802
|
+
*
|
|
803
|
+
* An ABSENT value (undefined / null / empty string) is acceptable: it means "no return URL", and
|
|
804
|
+
* every downstream consumer treats it that way via a truthiness check. Only a value the caller
|
|
805
|
+
* actually supplied is validated — otherwise omitting the field, or sending an empty one, would
|
|
806
|
+
* newly fail a request that has always worked.
|
|
807
|
+
*/
|
|
808
|
+
private isFrontendReturnUrlAcceptable(frontendReturnUrl: unknown): boolean {
|
|
809
|
+
if (!frontendReturnUrl) {
|
|
810
|
+
return true;
|
|
811
|
+
}
|
|
812
|
+
return typeof frontendReturnUrl === 'string' && this.parseAllowedFrontendReturnUrl(frontendReturnUrl) !== null;
|
|
813
|
+
}
|
|
814
|
+
|
|
699
815
|
/**
|
|
700
816
|
* Redirects to success page with state info.
|
|
701
817
|
* If a frontend return URL is provided, redirects there instead of the default success page.
|
|
702
818
|
*/
|
|
703
819
|
private redirectToSuccess(res: express.Response, state: string, connectionId: string, frontendReturnUrl?: string): void {
|
|
704
|
-
// If frontend return URL is provided, redirect there with
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
} catch (error) {
|
|
715
|
-
LogError(`[OAuth Callback] Invalid frontend return URL '${frontendReturnUrl}', falling back to default`);
|
|
716
|
-
// Fall through to default redirect
|
|
717
|
-
}
|
|
820
|
+
// If frontend return URL is provided and points at an allowed origin, redirect there with
|
|
821
|
+
// success parameters. Anything else falls through to the built-in page.
|
|
822
|
+
const url = frontendReturnUrl ? this.parseAllowedFrontendReturnUrl(frontendReturnUrl) : null;
|
|
823
|
+
if (url) {
|
|
824
|
+
url.searchParams.set('oauth', 'success');
|
|
825
|
+
url.searchParams.set('state', state);
|
|
826
|
+
url.searchParams.set('connectionId', connectionId);
|
|
827
|
+
LogStatus(`[OAuth Callback] Redirecting to frontend URL: ${url.toString()}`);
|
|
828
|
+
res.redirect(302, url.toString());
|
|
829
|
+
return;
|
|
718
830
|
}
|
|
719
831
|
|
|
720
832
|
// Default: redirect to built-in success page
|
|
721
|
-
const
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
res.redirect(302,
|
|
833
|
+
const defaultUrl = new URL(this.options.successRedirectUrl!);
|
|
834
|
+
defaultUrl.searchParams.set('state', state);
|
|
835
|
+
defaultUrl.searchParams.set('connectionId', connectionId);
|
|
836
|
+
res.redirect(302, defaultUrl.toString());
|
|
725
837
|
}
|
|
726
838
|
|
|
727
839
|
/**
|
|
@@ -729,27 +841,23 @@ export class OAuthCallbackHandler {
|
|
|
729
841
|
* If a frontend return URL is provided, redirects there instead of the default error page.
|
|
730
842
|
*/
|
|
731
843
|
private redirectToError(res: express.Response, errorCode: string, errorMessage: string, frontendReturnUrl?: string): void {
|
|
732
|
-
// If frontend return URL is provided, redirect there with
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
} catch (error) {
|
|
743
|
-
LogError(`[OAuth Callback] Invalid frontend return URL '${frontendReturnUrl}', falling back to default`);
|
|
744
|
-
// Fall through to default redirect
|
|
745
|
-
}
|
|
844
|
+
// If frontend return URL is provided and points at an allowed origin, redirect there with
|
|
845
|
+
// error parameters. Anything else falls through to the built-in page.
|
|
846
|
+
const url = frontendReturnUrl ? this.parseAllowedFrontendReturnUrl(frontendReturnUrl) : null;
|
|
847
|
+
if (url) {
|
|
848
|
+
url.searchParams.set('oauth', 'error');
|
|
849
|
+
url.searchParams.set('error', errorCode);
|
|
850
|
+
url.searchParams.set('error_description', errorMessage);
|
|
851
|
+
LogStatus(`[OAuth Callback] Redirecting to frontend URL with error: ${url.toString()}`);
|
|
852
|
+
res.redirect(302, url.toString());
|
|
853
|
+
return;
|
|
746
854
|
}
|
|
747
855
|
|
|
748
856
|
// Default: redirect to built-in error page
|
|
749
|
-
const
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
res.redirect(302,
|
|
857
|
+
const defaultUrl = new URL(this.options.errorRedirectUrl!);
|
|
858
|
+
defaultUrl.searchParams.set('error', errorCode);
|
|
859
|
+
defaultUrl.searchParams.set('error_description', errorMessage);
|
|
860
|
+
res.redirect(302, defaultUrl.toString());
|
|
753
861
|
}
|
|
754
862
|
|
|
755
863
|
/**
|