-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathutil.ts
More file actions
935 lines (821 loc) · 25.9 KB
/
Copy pathutil.ts
File metadata and controls
935 lines (821 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
import { randomFill } from 'node:crypto';
import { isIPv4, isIPv6 } from 'node:net';
import { S3ClientConfig } from '@aws-sdk/client-s3';
import { HandlerContext } from '@connectrpc/connect';
import * as Sentry from '@sentry/node';
import {
GraphQLSubscriptionProtocol,
GraphQLWebsocketSubprotocol,
} from '@wundergraph/cosmo-connect/dist/common/common_pb';
import { joinLabel, splitLabel } from '@wundergraph/cosmo-shared';
import { AxiosError } from 'axios';
import { isNetworkError, isRetryableError } from 'axios-retry';
import { formatISO, subHours } from 'date-fns';
import { FastifyBaseLogger } from 'fastify';
import { parse, visit } from 'graphql';
import { uid } from 'uid/secure';
import DOMPurify from 'isomorphic-dompurify';
import { LATEST_ROUTER_COMPATIBILITY_VERSION } from '@wundergraph/composition';
import { ProposalOrigin, SubgraphType } from '@wundergraph/cosmo-connect/dist/platform/v1/platform_pb';
import { MemberRole, ProposalOrigin as ProposalOriginEnum, WebsocketSubprotocol } from '../db/models.js';
import { AuthContext, DateRange, FederatedGraphDTO, Label, ResponseMessage, S3StorageOptions } from '../types/index.js';
import { paginationDefaults } from './constants.js';
import { isAuthenticationError, isAuthorizationError, isPublicError } from './errors/errors.js';
import { GraphKeyAuthContext } from './services/GraphApiTokenAuthenticator.js';
const labelRegex = /^[\dA-Za-z](?:[\w.-]{0,61}[\dA-Za-z])?$/;
const namespaceRegex = /^[\da-z]+(?:[_-][\da-z]+)*$/;
const schemaTagRegex = /^(?![/-])[\d/A-Za-z-]+(?<![/-])$/;
const graphNameRegex = /^[\dA-Za-z]+(?:[./@_-][\dA-Za-z]+)*$/;
const pluginVersionRegex = /^v\d+$/;
/**
* Wraps a function with a try/catch block and logs any errors that occur.
* If the error is a public error, it is returned as a response message.
* Otherwise, the error is rethrown so that it can be handled by the connect framework.
*/
export async function handleError<T extends ResponseMessage>(
ctx: HandlerContext,
defaultLogger: FastifyBaseLogger,
fn: () => Promise<T> | T,
): Promise<T> {
try {
return await fn();
} catch (error: any) {
// Get enriched logger here. Enriching logger happens within the above function call.
const logger = getLogger(ctx, defaultLogger);
if (isAuthenticationError(error)) {
return {
response: {
code: error.code,
details: error.message,
},
} as T;
} else if (isPublicError(error)) {
return {
response: {
code: error.code,
details: error.message,
},
} as T;
} else if (isAuthorizationError(error)) {
return {
response: {
code: error.code,
details: error.message,
},
} as T;
}
logger.error(error);
throw error;
}
}
export const fastifyLoggerId = Symbol('logger');
export const sentrySpanId = Symbol('sentrySpan');
export const getLogger = (ctx: HandlerContext, defaultLogger: FastifyBaseLogger) => {
return ctx.values.get<FastifyBaseLogger>({ id: fastifyLoggerId, defaultValue: defaultLogger });
};
export const enrichLogger = (
ctx: HandlerContext,
logger: FastifyBaseLogger,
authContext: Partial<AuthContext & GraphKeyAuthContext>,
) => {
const newLogger = logger.child({
service: ctx.service.typeName,
method: ctx.method.name,
actor: {
userId: authContext.userId,
organizationId: authContext.organizationId,
},
});
ctx.values.set<FastifyBaseLogger>({ id: fastifyLoggerId, defaultValue: newLogger }, newLogger);
Sentry.setUser({
id: authContext.userId,
username: authContext.userDisplayName,
});
const spanAttributes = Object.fromEntries(
Object.entries({
'user.id': authContext.userId,
'user.displayName': authContext.userDisplayName,
'organization.id': authContext.organizationId,
'organization.slug': authContext.organizationSlug,
}).filter(([, v]) => v),
);
const activeSpan = Sentry.getActiveSpan();
if (activeSpan) {
Sentry.getRootSpan(activeSpan).setAttributes(spanAttributes);
}
return newLogger;
};
export function createRandomInternalLabel(): Label {
return {
key: '_internal',
value: uid(6),
};
}
/**
* Normalizes labels by removing duplicates.
* Also performs a simple sort
*/
export function normalizeLabels(labels: Label[]): Label[] {
const concatenatedLabels = labels.map((l) => joinLabel(l)).sort();
const uniqueLabels = new Set(concatenatedLabels);
return [...uniqueLabels].map((label) => splitLabel(label));
}
export function isValidSchemaTag(tag: string): boolean {
if (!tag) {
return false;
}
if (tag.length > 128) {
return false;
}
if (!schemaTagRegex.test(tag)) {
return false;
}
return true;
}
export function isValidSchemaTags(tags: string[]): boolean {
for (const tag of tags) {
if (!isValidSchemaTag(tag)) {
return false;
}
}
return true;
}
/**
* Both key and value must be 63 characters or fewer (cannot be empty).
* Must begin and end with an alphanumeric character ([a-z0-9A-Z]).
* Could contain dashes (-), underscores (_), dots (.), and alphanumerics between.
*/
export function isValidLabels(labels: Label[]): boolean {
for (const label of labels) {
const { key, value } = label;
// key and value cannot be empty
if (!key || !value) {
return false;
}
// key and value must follow a specific pattern
if (!labelRegex.test(key) || !labelRegex.test(value)) {
return false;
}
}
return true;
}
export function isValidLabelMatchers(labelMatchers: string[]): boolean {
for (const lm of labelMatchers) {
const labels = lm.split(',').map((l) => splitLabel(l));
if (!isValidLabels(labels)) {
return false;
}
}
return true;
}
export function normalizeLabelMatchers(labelMatchers: string[]): string[] {
const normalizedMatchers: string[] = [];
for (const lm of labelMatchers) {
const labels = lm.split(',').map((l) => splitLabel(l));
const normalizedLabels = normalizeLabels(labels);
normalizedMatchers.push(normalizedLabels.map((nl) => joinLabel(nl)).join(','));
}
// We previously deduplicate and sort the labels. Now we deduplicate the matchers.
return [...new Set(normalizedMatchers)];
}
export function base64URLEncode(str: Buffer) {
return str.toString('base64url');
}
export function randomToken() {
return uid(32);
}
export function randomString(length: number): Promise<string> {
const buf = Buffer.alloc(length);
return new Promise((resolve, reject) => {
randomFill(buf, (err, buf) => {
if (err) {
reject(err);
return;
}
resolve(base64URLEncode(buf));
});
});
}
export function sanitizeMigratedGraphName(input: string): string {
if (labelRegex.test(input)) {
return input;
}
return `migrated_graph_${uid(12)}`;
}
export const formatSubscriptionProtocol = (protocol: GraphQLSubscriptionProtocol) => {
switch (protocol) {
case GraphQLSubscriptionProtocol.GRAPHQL_SUBSCRIPTION_PROTOCOL_WS: {
return 'ws';
}
case GraphQLSubscriptionProtocol.GRAPHQL_SUBSCRIPTION_PROTOCOL_SSE: {
return 'sse';
}
case GraphQLSubscriptionProtocol.GRAPHQL_SUBSCRIPTION_PROTOCOL_SSE_POST: {
return 'sse_post';
}
}
};
export const formatWebsocketSubprotocol = (protocol: GraphQLWebsocketSubprotocol): WebsocketSubprotocol => {
switch (protocol) {
case GraphQLWebsocketSubprotocol.GRAPHQL_WEBSOCKET_SUBPROTOCOL_AUTO: {
return 'auto';
}
case GraphQLWebsocketSubprotocol.GRAPHQL_WEBSOCKET_SUBPROTOCOL_WS: {
return 'graphql-ws';
}
case GraphQLWebsocketSubprotocol.GRAPHQL_WEBSOCKET_SUBPROTOCOL_TRANSPORT_WS: {
return 'graphql-transport-ws';
}
}
};
export const hasLabelsChanged = (prev: Label[], cur: Label[]): boolean => {
if (prev.length !== cur.length) {
return true;
}
// This works fine because we don't allow comma in the label key or value,
// so we can use it as a separator to compare the labels
return (
prev
.map((p) => joinLabel(p))
.sort()
.join(',') !==
cur
.map((c) => joinLabel(c))
.sort()
.join(',')
);
};
// checks if the user has the right roles to perform the operation.
export const checkUserAccess = ({ rolesToBe, userRoles }: { rolesToBe: MemberRole[]; userRoles: MemberRole[] }) => {
for (const role of rolesToBe) {
if (userRoles.includes(role)) {
return true;
}
}
return false;
};
export const getHighestPriorityRole = ({ userRoles }: { userRoles: string[] }) => {
if (userRoles.includes('admin')) {
return 'admin';
}
if (userRoles.includes('developer')) {
return 'developer';
}
return 'viewer';
};
export const isValidNamespaceName = (name: string): boolean => {
return namespaceRegex.test(name);
};
export const isValidGraphName = (name: string): boolean => {
if (name.length === 0 || name.length > 100) {
return false;
}
return graphNameRegex.test(name);
};
export const isValidPluginVersion = (version: string): boolean => {
return pluginVersionRegex.test(version);
};
export const validateDateRanges = ({
limit,
range,
dateRange,
}: {
limit: number;
range?: number;
dateRange?: DateRange;
}): { range: number | undefined; dateRange: DateRange | undefined } => {
let validatedRange: number | undefined = range;
const validatedDateRange: DateRange | undefined = dateRange;
if (validatedRange && validatedRange > limit * 24) {
validatedRange = limit * 24;
}
if (validatedDateRange) {
const startDate = new Date(validatedDateRange.start);
const endDate = new Date(validatedDateRange.end);
if (startDate > endDate || endDate < subHours(new Date(), limit * 24)) {
return {
range: validatedRange,
dateRange: undefined,
};
}
if (startDate < subHours(new Date(), limit * 24)) {
validatedDateRange.start = formatISO(subHours(new Date(), limit * 24));
}
}
return {
range: validatedRange,
dateRange: validatedDateRange,
};
};
export const extractOperationNames = (contents: string): string[] => {
// parse contents using graphql library and extract operation names
// return operation names
const names: string[] = [];
const doc = parse(contents);
visit(doc, {
OperationDefinition(node) {
const operationName = node.name?.value ?? '';
if (operationName) {
names.push(operationName);
}
},
});
return names;
};
export function getValueOrDefault<K, V>(map: Map<K, V>, key: K, constructor: () => V): V {
const existingValue = map.get(key);
if (existingValue) {
return existingValue;
}
const value = constructor();
map.set(key, value);
return value;
}
// webhookAxiosRetryCond retry condition function to retry on network errors and 429, 5xx errors for all
// HTTP methods including POST, PUT, DELETE, etc.
export function webhookAxiosRetryCond(err: AxiosError) {
return isNetworkError(err) || isRetryableError(err);
}
/**
* Determines whether the given string is a Google Cloud Storage address by checking whether the hostname is
* `storage.googleapis.com` or the protocol is `gs:`.
*/
export function isGoogleCloudStorageUrl(s: string): boolean {
if (!s) {
return false;
}
try {
const url = new URL(s);
const hostname = url.hostname.toLowerCase();
return (
url.protocol === 'gs:' || hostname === 'storage.googleapis.com' || hostname.endsWith('.storage.googleapis.com')
);
} catch {
// ignore
}
return false;
}
export function createS3ClientConfig(bucketName: string, opts: S3StorageOptions): S3ClientConfig {
const url = new URL(opts.url);
const { region, username, password } = opts;
const forcePathStyle = opts.forcePathStyle ?? !isVirtualHostStyleUrl(url);
const endpoint = opts.endpoint || (forcePathStyle ? url.origin : url.origin.replace(`${bucketName}.`, ''));
const accessKeyId = url.username || username || '';
const secretAccessKey = url.password || password || '';
if (!accessKeyId || !secretAccessKey) {
throw new Error('Missing S3 credentials. Please provide access key ID and secret access key.');
}
if (!region) {
throw new Error('Missing region in S3 configuration.');
}
return {
region,
endpoint,
credentials: {
accessKeyId,
secretAccessKey,
},
forcePathStyle,
};
}
export function extractS3BucketName(opts: S3StorageOptions) {
const url = new URL(opts.url);
if (opts.forcePathStyle || !isVirtualHostStyleUrl(url)) {
return url.pathname.slice(1);
}
return url.hostname.split('.')[0];
}
export function isVirtualHostStyleUrl(url: URL) {
return url.hostname.split('.').length > 2;
}
export function mergeUrls(baseUrl: string, relativeUrl: string) {
// Remove the leading slash beacuse if the relative URL starts with a slash,
// the relative part will merge with only the hostname ignoring the rest of the base url if any.
relativeUrl = relativeUrl.startsWith('/') ? relativeUrl.slice(1) : relativeUrl;
// Same as the above case, if the base URL doesnt end with a slash,
// the computed url will only have the host and the relative URL and will ignore the rest of the base URL if any.
baseUrl = baseUrl.endsWith('/') ? baseUrl : baseUrl + '/';
return new URL(relativeUrl, baseUrl).toString();
}
export function createBatches<T>(array: T[], batchSize: number): T[][] {
const batches: T[][] = [];
for (let i = 0; i < array.length; i += batchSize) {
const batch = array.slice(i, i + batchSize);
batches.push(batch);
}
return batches;
}
/**
* Distributes a limit across multiple arrays that are logically grouped.
* Arrays are processed in order, with earlier arrays having priority.
*
* Example: limitCombinedArrays([errors, warnings], 50)
* - If errors has 70 items and warnings has 10 items: returns [50 errors, 0 warnings]
* - If errors has 30 items and warnings has 30 items: returns [30 errors, 20 warnings]
* - If errors has 10 items and warnings has 70 items: returns [10 errors, 40 warnings]
*
* @param arrays The arrays to limit (order determines priority)
* @param limit The combined maximum number of items across all arrays
* @returns The limited arrays in the same order as input
*/
export function limitCombinedArrays<T>(arrays: T[][], limit: number | null): T[][] {
if (arrays.length === 0) {
return [];
}
if (limit == null) {
return arrays;
}
const result: T[][] = [];
let remaining = limit;
// Process arrays in order, taking as much as possible from each
for (const arr of arrays) {
if (remaining === 0) {
result.push([]);
} else {
const itemsToTake = Math.min(arr.length, remaining);
result.push(arr.slice(0, itemsToTake));
remaining -= itemsToTake;
}
}
return result;
}
export const checkIfLabelMatchersChanged = (data: {
isContract: boolean;
currentLabelMatchers: string[];
newLabelMatchers: string[];
unsetLabelMatchers?: boolean;
}) => {
if (data.isContract && data.newLabelMatchers.length === 0) {
return false;
}
// User tries to unset but no matchers exist, then nothing has changed
if (data.unsetLabelMatchers && data.currentLabelMatchers.length === 0) {
return false;
}
// If user tries to unset but matchers exist, then it has changed
if (data.unsetLabelMatchers) {
return true;
}
// Not a contract, not unsetting, no new matchers, then nothing has changed
if (data.newLabelMatchers.length === 0) {
return false;
}
// Not a contract, not unsetting but new matchers are passed, we need to check if they are different
if (data.newLabelMatchers.length !== data.currentLabelMatchers.length) {
return true;
}
for (const labelMatcher of data.newLabelMatchers) {
if (!data.currentLabelMatchers.includes(labelMatcher)) {
return true;
}
}
return false;
};
export function getFederatedGraphRouterCompatibilityVersion(federatedGraphDTOs: Array<FederatedGraphDTO>): string {
if (federatedGraphDTOs.length === 0) {
return LATEST_ROUTER_COMPATIBILITY_VERSION;
}
return federatedGraphDTOs[0].routerCompatibilityVersion;
}
export function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
/**
* Normalizes pagination parameters by applying defaults and clamping to safe bounds.
* Uses the standard pagination defaults from constants unless overridden.
*/
export function normalizePagination(
opts: { limit?: number; offset?: number },
overrides?: { maxLimit?: number; maxOffset?: number },
): { limit: number; offset: number } {
const maxLimit = overrides?.maxLimit ?? paginationDefaults.maxLimit;
const maxOffset = overrides?.maxOffset ?? paginationDefaults.maxOffset;
return {
limit: clamp(opts.limit || paginationDefaults.defaultLimit, paginationDefaults.minLimit, maxLimit),
offset: clamp(opts.offset || 0, paginationDefaults.minOffset, maxOffset),
};
}
export const isCheckSuccessful = ({
isComposable,
isBreaking,
hasClientTraffic,
hasLintErrors,
hasGraphPruningErrors,
clientTrafficCheckSkipped,
hasProposalMatchError,
isLinkedTrafficCheckFailed,
isLinkedPruningCheckFailed,
checkExtensionDeliveryId,
checkExtensionErrorMessage,
}: {
isComposable: boolean;
isBreaking: boolean;
hasClientTraffic: boolean;
hasLintErrors: boolean;
hasGraphPruningErrors: boolean;
clientTrafficCheckSkipped: boolean;
hasProposalMatchError: boolean;
isLinkedTrafficCheckFailed?: boolean;
isLinkedPruningCheckFailed?: boolean;
checkExtensionDeliveryId?: string;
checkExtensionErrorMessage?: string;
}) => {
// if a subgraph is linked to another subgraph, then the status of the check depends on the traffic and pruning check of the linked subgraph
if (isLinkedTrafficCheckFailed || isLinkedPruningCheckFailed) {
return false;
}
if (checkExtensionDeliveryId && checkExtensionErrorMessage) {
return false;
}
return (
isComposable &&
// If no breaking changes found
// OR Breaking changes are found, but no client traffic is found and traffic check is not skipped
(!isBreaking || (isBreaking && !hasClientTraffic && !clientTrafficCheckSkipped)) &&
!hasLintErrors &&
!hasGraphPruningErrors &&
!hasProposalMatchError
);
};
export const flipDateRangeValuesIfNeeded = (dateRange?: { start: number; end: number }) => {
if (!dateRange || dateRange.start <= dateRange.end) {
return;
}
const tmp = dateRange.start;
dateRange.start = dateRange.end;
dateRange.end = tmp;
};
export const formatSubgraphType = (type: SubgraphType) => {
switch (type) {
case SubgraphType.STANDARD: {
return 'standard';
}
case SubgraphType.GRPC_PLUGIN: {
return 'grpc_plugin';
}
case SubgraphType.GRPC_SERVICE: {
return 'grpc_service';
}
default: {
throw new Error(`Unknown subgraph type: ${type}`);
}
}
};
export const convertToSubgraphType = (type: string) => {
switch (type) {
case 'standard': {
return SubgraphType.STANDARD;
}
case 'grpc_plugin': {
return SubgraphType.GRPC_PLUGIN;
}
case 'grpc_service': {
return SubgraphType.GRPC_SERVICE;
}
default: {
throw new Error(`Unknown subgraph type: ${type}`);
}
}
};
export function toProposalOriginEnum(value: ProposalOrigin): ProposalOriginEnum {
switch (value) {
case ProposalOrigin.EXTERNAL: {
return 'EXTERNAL';
}
default: {
return 'INTERNAL';
}
}
}
export function fromProposalOriginEnum(value: ProposalOriginEnum): ProposalOrigin {
switch (value) {
case 'EXTERNAL': {
return ProposalOrigin.EXTERNAL;
}
default: {
return ProposalOrigin.INTERNAL;
}
}
}
export function sanitizeReadme(value: string | undefined | null): string | null {
if (value === null || value === undefined) {
return null;
}
const trimmedValue = value.trim();
return trimmedValue.length === 0 ? null : DOMPurify.sanitize(trimmedValue);
}
export function isValidLocalhostOrSecureEndpoint(value: string) {
if (!value) {
return false;
}
let isValid = false;
try {
const endpoint = new URL(value);
isValid =
(endpoint.hostname === 'localhost' && (endpoint.protocol === 'http:' || endpoint.protocol === 'https:')) ||
(endpoint.hostname !== 'localhost' && endpoint.protocol === 'https:');
} catch {
// ignore
}
return isValid;
}
function isValidPort(port: string | undefined): boolean {
if (port === undefined) {
return true;
}
if (!/^\d+$/.test(port)) {
return false;
}
const portNum = Number.parseInt(port, 10);
// Valid port range is 1-65535 (port 0 is reserved)
return portNum >= 1 && portNum <= 65_535;
}
function isValidHostname(hostname: string): boolean {
if (!hostname || hostname.length > 253) {
return false;
}
const labels = hostname.split('.');
return labels.every((label) => /^[\da-z](?:[\da-z-]{0,61}[\da-z])?$/i.test(label));
}
function isValidHostOrIpv4(host: string): boolean {
return isIPv4(host) || isValidHostname(host);
}
function isValidHostPort(target: string): boolean {
if (!target || target.includes('/')) {
return false;
}
const lastColonIndex = target.lastIndexOf(':');
if (lastColonIndex === -1) {
return isValidHostOrIpv4(target);
}
if (target.indexOf(':') !== lastColonIndex) {
return false;
}
const host = target.slice(0, lastColonIndex);
const port = target.slice(lastColonIndex + 1);
if (!host || !port) {
return false;
}
return isValidHostOrIpv4(host) && isValidPort(port);
}
function isValidDnsTarget(rest: string): boolean {
if (!rest) {
return false;
}
if (rest.startsWith('//')) {
const remainder = rest.slice(2);
if (!remainder) {
return false;
}
const slashIndex = remainder.indexOf('/');
const endpoint = slashIndex === -1 ? remainder : remainder.slice(slashIndex + 1);
return isValidHostPort(endpoint);
}
return isValidHostPort(rest);
}
/**
* Validates if a routing URL is using one of the supported gRPC naming schemes.
* Supported schemes: dns:, unix:, unix-abstract:, vsock:, ipv4:, ipv6:
*/
export function isValidGrpcNamingScheme(url: string): boolean {
const value = url.trim();
if (!value) {
return false;
}
const supportedSchemes = new Set(['dns', 'unix', 'unix-abstract', 'vsock', 'ipv4', 'ipv6']);
const schemeMatch = /^([a-z][\d+.a-z-]*):/i.exec(value);
if (!schemeMatch) {
return isValidDnsTarget(value);
}
const scheme = schemeMatch[1].toLowerCase();
const rest = value.slice(schemeMatch[0].length);
if (!supportedSchemes.has(scheme)) {
return isValidDnsTarget(value);
}
switch (scheme) {
case 'dns': {
if (rest.startsWith('//')) {
const remainder = rest.slice(2);
const slashIndex = remainder.indexOf('/');
if (slashIndex === -1) {
return false; // No host:port path found
}
const endpoint = remainder.slice(slashIndex + 1);
if (!endpoint) {
return false; // Empty endpoint after slash
}
return isValidHostPort(endpoint);
}
return isValidDnsTarget(rest);
}
case 'unix': {
if (!rest) {
return false;
}
let path = rest;
if (rest.startsWith('//')) {
const remainder = rest.slice(2);
const slashIndex = remainder.indexOf('/');
path = slashIndex === -1 ? '' : remainder.slice(slashIndex);
}
return path.length > 0 && path !== '/';
}
case 'unix-abstract': {
return rest.length > 0;
}
case 'vsock': {
const parts = rest.split(':');
if (parts.length !== 2) {
return false;
}
const [cid, port] = parts;
if (!/^\d+$/.test(cid) || !/^\d+$/.test(port)) {
return false;
}
// Validate port range (1-65535)
return isValidPort(port);
}
case 'ipv4': {
if (!rest) {
return false;
}
const endpoints = rest.split(',').map((endpoint) => endpoint.trim());
return endpoints.every((endpoint) => {
if (!endpoint) {
return false;
}
const lastColonIndex = endpoint.lastIndexOf(':');
if (lastColonIndex === -1) {
return isIPv4(endpoint);
}
if (endpoint.indexOf(':') !== lastColonIndex) {
return false;
}
const host = endpoint.slice(0, lastColonIndex);
const port = endpoint.slice(lastColonIndex + 1);
return isIPv4(host) && isValidPort(port);
});
}
case 'ipv6': {
if (!rest) {
return false;
}
const endpoints = rest.split(',').map((endpoint) => endpoint.trim());
return endpoints.every((endpoint) => {
if (!endpoint) {
return false;
}
if (endpoint.startsWith('[')) {
const closingIndex = endpoint.indexOf(']');
if (closingIndex === -1) {
return false;
}
const address = endpoint.slice(1, closingIndex);
if (!isIPv6(address)) {
return false;
}
const portPart = endpoint.slice(closingIndex + 1);
if (!portPart) {
return true;
}
if (!portPart.startsWith(':')) {
return false;
}
return isValidPort(portPart.slice(1));
}
return isIPv6(endpoint);
});
}
default: {
return false;
}
}
}
/**
* Validates a routing URL accepted for a GRPC_SERVICE subgraph. The router
* can reach a gRPC subgraph over either native gRPC (via the gRPC name
* resolver schemes) or ConnectRPC over HTTP/1.1, and the protocol is chosen
* at request time by the router via the `grpc_protocol` configuration block.
*
* Accepts:
* - any URL using one of the gRPC naming schemes recognised by
* isValidGrpcNamingScheme (dns:, unix:, unix-abstract:, vsock:, ipv4:, ipv6:),
* - any well-formed http:// or https:// URL.
*/
export function isValidGrpcSubgraphRoutingURL(url: string): boolean {
const value = url.trim();
if (!value) {
return false;
}
const lower = value.toLowerCase();
if (lower.startsWith('http://') || lower.startsWith('https://')) {
try {
// eslint-disable-next-line no-new
new URL(value);
return true;
} catch {
return false;
}
}
return isValidGrpcNamingScheme(value);
}