-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathConfigUtils.ts
More file actions
281 lines (237 loc) · 8.41 KB
/
Copy pathConfigUtils.ts
File metadata and controls
281 lines (237 loc) · 8.41 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
// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
import { readFileSync, existsSync } from 'fs'
import { Config, RawConfig, rawConfigSchema } from './Config.js'
import { Env } from '../env.js'
export class ConfigUtils {
static loadConfigFile(filePath: string): Config {
if (existsSync(filePath)) {
const rawJson = JSON.parse(readFileSync(filePath, 'utf-8'))
const normalizedJson = normalizeConfigUrls(rawJson)
const rawConfig = rawConfigSchema.parse(normalizedJson)
const config = resolveRawConfig(rawConfig)
/**
* Perform extra config validation beyond schema validation.
* We want to enforce the following constraints:
*
* 1. IDP IDs are unique
* 2. Network IDs are unique
* 3. Each Network's identityProviderId maps to an existing IDP (in config)
* 4. Each Network's auth method is compatible with its IDP type
*/
const duplicateIdpId = hasDuplicateElement(
config.bootstrap.idps.map((idp) => idp.id)
)
if (duplicateIdpId) {
throw new Error(
`Non-unique IDP IDs found in config file: ${duplicateIdpId}`
)
}
const duplicateNetworkId = hasDuplicateElement(
config.bootstrap.networks.map((network) => network.id)
)
if (duplicateNetworkId) {
throw new Error(
`Non-unique Network IDs found in config file: ${duplicateNetworkId}`
)
}
const invalidMapping = validateNetworkToIdpMapping(config)
if (invalidMapping) {
throw new Error(
`Network ${invalidMapping.networkId} references unknown Identity Provider ID ${invalidMapping.idpId}`
)
}
const invalidAuthMethod = validateNetworkAuthMethods(config)
if (invalidAuthMethod) {
throw new Error(
`Network ${invalidAuthMethod.networkId} has invalid auth method ${invalidAuthMethod.invalidAuthMethod} for its Identity Provider`
)
}
return config
} else {
throw new Error("Supplied file path doesn't exist " + filePath)
}
}
}
function normalizeConfigUrls(input: unknown): unknown {
if (!input || typeof input !== 'object') {
return input
}
const candidate = input as {
bootstrap?: {
idps?: Array<{ issuer?: string }>
networks?: Array<{ ledgerApi?: { baseUrl?: string } }>
}
}
const idps = candidate.bootstrap?.idps
if (Array.isArray(idps)) {
for (const idp of idps) {
const issuer = idp.issuer
if (typeof issuer === 'string' && shouldNormalizeAsUrl(issuer)) {
idp.issuer = normalizeBaseUrl(issuer)
}
}
}
const networks = candidate.bootstrap?.networks
if (Array.isArray(networks)) {
for (const network of networks) {
const baseUrl = network.ledgerApi?.baseUrl
if (typeof baseUrl === 'string') {
network.ledgerApi!.baseUrl = normalizeBaseUrl(baseUrl)
}
}
}
return input
}
function shouldNormalizeAsUrl(value: string): boolean {
const trimmed = value.trim()
// Preserve non-URL issuers for self-signed setups, e.g. "unsafe-auth".
if (
!trimmed.includes('://') &&
!trimmed.includes('.') &&
!trimmed.includes(':')
) {
return trimmed.toLowerCase() === 'localhost'
}
return true
}
function normalizeBaseUrl(baseUrl: string): string {
const trimmed = baseUrl.trim()
if (trimmed.length === 0) {
return baseUrl
}
if (trimmed.includes('://')) {
return normalizeUrlWithProtocol(new URL(trimmed))
}
const withDefaultProtocol = new URL(`http://${trimmed}`)
const hasExplicitPort = hasPortInAuthority(trimmed)
if (!hasExplicitPort) {
withDefaultProtocol.port = '80'
}
return normalizeUrlWithProtocol(withDefaultProtocol)
}
function hasPortInAuthority(rawValue: string): boolean {
const authority = rawValue.split(/[/?#]/)[0]
// IPv6 literal with explicit port, e.g. [::1]:5003
if (authority.startsWith('[')) {
return authority.includes(']:')
}
return authority.includes(':')
}
function normalizeUrlWithProtocol(url: URL): string {
const defaultPort =
url.protocol === 'http:' ? '80' : url.protocol === 'https:' ? '443' : ''
const port = url.port || defaultPort
const hostname = url.hostname.includes(':')
? `[${url.hostname}]`
: url.hostname
const authority = port ? `${hostname}:${port}` : hostname
const path =
url.pathname === '/' && !url.search && !url.hash
? ''
: `${url.pathname}${url.search}${url.hash}`
return `${url.protocol}//${authority}${path}`
}
type RawNetworkAuth = NonNullable<
RawConfig['bootstrap']['networks'][number]['adminAuth']
>
type NetworkAuth = NonNullable<
Config['bootstrap']['networks'][number]['adminAuth']
>
// The Wallet Gateway can accept adminAuth secrets from environment variables.
// However, the store expects strings. This function resolves the config from env vars
function resolveRawNetworkAuth(n: RawNetworkAuth): NetworkAuth {
if (n.method === 'authorization_code') {
return n
}
if ('clientSecret' in n) {
return n
} else {
const { clientSecretEnv, ...rest } = n
const clientSecret = Env.get(clientSecretEnv, { required: true })
return {
...rest,
clientSecret,
}
}
}
function resolveRawConfig(rawConfig: RawConfig): Config {
const rawNetworks = rawConfig.bootstrap.networks
const networks: Config['bootstrap']['networks'] = rawNetworks.map((n) => {
return {
...n,
auth: resolveRawNetworkAuth(n.auth),
adminAuth: n.adminAuth
? resolveRawNetworkAuth(n.adminAuth)
: undefined,
}
})
return {
...rawConfig,
bootstrap: {
...rawConfig.bootstrap,
networks,
},
}
}
function hasDuplicateElement(list: string[]): string | undefined {
let duplicate: string | undefined
list.forEach((item, i) => {
if (list.indexOf(item) !== i && duplicate === undefined) {
duplicate = item
}
})
return duplicate
}
function validateNetworkToIdpMapping(
config: Config
): { networkId: string; idpId: string } | undefined {
for (const network of config.bootstrap.networks) {
const idp = config.bootstrap.idps.find(
(idp) => idp.id === network.identityProviderId
)
if (typeof idp === 'undefined') {
return { networkId: network.id, idpId: network.identityProviderId }
}
}
}
const SUPPORTED_IDP_METHODS = {
self_signed: ['self_signed'],
oauth: ['authorization_code', 'client_credentials'],
}
function validateNetworkAuthMethods(
config: Config
): { networkId: string; invalidAuthMethod: string } | undefined {
for (const network of config.bootstrap.networks) {
const idp = config.bootstrap.idps.find(
(idp) => idp.id === network.identityProviderId
)!
if (!SUPPORTED_IDP_METHODS[idp.type].includes(network.auth.method)) {
return {
networkId: network.id,
invalidAuthMethod: network.auth.method,
}
}
}
}
interface Urls {
serviceUrl: string
publicUrl: string
dappApiUrl: string
userApiUrl: string
}
// Strips duplicate slashes from a URL, except for the protocol part (e.g., "http://")
function stripDuplicateSlashes(path: string): string {
return path.replace(/(https?:\/\/)|(\/)+/g, '$1$2')
}
export const deriveUrls = (config: Config, port?: number): Urls => {
const serviceUrl = `http://localhost:${port || config.server.port}`
const publicUrl = config.kernel.publicUrl || serviceUrl
const dappApiUrl = stripDuplicateSlashes(
`${publicUrl}/${config.server.dappPath}`
)
const userApiUrl = stripDuplicateSlashes(
`${publicUrl}/${config.server.userPath}`
)
return { dappApiUrl, userApiUrl, publicUrl, serviceUrl }
}