|
7 | 7 | import fs from 'node:fs';
|
8 | 8 | import path from 'node:path';
|
9 | 9 | import { Org, SfError } from '@salesforce/core';
|
| 10 | +import axios from 'axios'; |
10 | 11 |
|
11 | 12 | export type SiteMetadata = {
|
12 | 13 | bundleName: string;
|
@@ -94,6 +95,28 @@ export class ExperienceSite {
|
94 | 95 | return experienceSites;
|
95 | 96 | }
|
96 | 97 |
|
| 98 | + /** |
| 99 | + * Esablish a valid token for this local development session |
| 100 | + * |
| 101 | + * @returns sid token for proxied site requests |
| 102 | + */ |
| 103 | + public async setupAuth(): Promise<string> { |
| 104 | + let sidToken = ''; // Default to guest user access only |
| 105 | + |
| 106 | + // Use environment variable for now if users want to just have guest access only |
| 107 | + if (process.env.SITE_GUEST_ACCESS !== 'true') { |
| 108 | + try { |
| 109 | + const networkId = await this.getNetworkId(); |
| 110 | + sidToken = await this.getNewSidToken(networkId); |
| 111 | + } catch (e) { |
| 112 | + // eslint-disable-next-line no-console |
| 113 | + console.error('Failed to establish authentication for site', e); |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + return sidToken; |
| 118 | + } |
| 119 | + |
97 | 120 | public async isUpdateAvailable(): Promise<boolean> {
|
98 | 121 | const localMetadata = this.getLocalMetadata();
|
99 | 122 | if (!localMetadata) {
|
@@ -225,6 +248,99 @@ export class ExperienceSite {
|
225 | 248 |
|
226 | 249 | return resourcePath;
|
227 | 250 | }
|
| 251 | + |
| 252 | + private async getNetworkId(): Promise<string> { |
| 253 | + const conn = this.org.getConnection(); |
| 254 | + // Query the Network object for the network with the given site name |
| 255 | + const result = await conn.query<{ Id: string }>(`SELECT Id FROM Network WHERE Name = '${this.siteDisplayName}'`); |
| 256 | + |
| 257 | + const record = result.records[0]; |
| 258 | + if (record) { |
| 259 | + let networkId = record.Id; |
| 260 | + // Subtract the last three characters from the Network ID |
| 261 | + networkId = networkId.substring(0, networkId.length - 3); |
| 262 | + return networkId; |
| 263 | + } else { |
| 264 | + throw new Error(`NetworkId for site: '${this.siteDisplayName}' could not be found`); |
| 265 | + } |
| 266 | + } |
| 267 | + |
| 268 | + private async getNewSidToken(networkId: string): Promise<string> { |
| 269 | + // Get the connection and access token from the org |
| 270 | + const conn = this.org.getConnection(); |
| 271 | + const orgId = this.org.getOrgId(); |
| 272 | + |
| 273 | + // Not sure if we need to do this |
| 274 | + const orgIdMinus3 = orgId.substring(0, orgId.length - 3); |
| 275 | + const accessToken = conn.accessToken; |
| 276 | + const instanceUrl = conn.instanceUrl; // Org URL |
| 277 | + |
| 278 | + // Make the GET request without following redirects |
| 279 | + if (accessToken) { |
| 280 | + // TODO should we try and refresh auth here? |
| 281 | + // await conn.refreshAuth(); |
| 282 | + |
| 283 | + // Call out to the switcher servlet to establish a session |
| 284 | + const switchUrl = `${instanceUrl}/servlet/networks/switch?networkId=${networkId}`; |
| 285 | + const cookies = [`sid=${accessToken}`, `oid=${orgIdMinus3}`].join('; ').trim(); |
| 286 | + let response = await axios.get(switchUrl, { |
| 287 | + headers: { |
| 288 | + Cookie: cookies, |
| 289 | + }, |
| 290 | + withCredentials: true, |
| 291 | + maxRedirects: 0, // Prevent axios from following redirects |
| 292 | + validateStatus: (status) => status >= 200 && status < 400, // Accept 3xx status codes |
| 293 | + }); |
| 294 | + |
| 295 | + // Extract the Location callback header |
| 296 | + const locationHeader = response.headers['location'] as string; |
| 297 | + if (locationHeader) { |
| 298 | + // Parse the URL to extract the 'sid' parameter |
| 299 | + const urlObj = new URL(locationHeader); |
| 300 | + const sid = urlObj.searchParams.get('sid') ?? ''; |
| 301 | + const cookies2 = ['__Secure-has-sid=1', `sid=${sid}`, `oid=${orgIdMinus3}`].join('; ').trim(); |
| 302 | + |
| 303 | + // Request the location header to establish our session with the servlet |
| 304 | + response = await axios.get(urlObj.toString(), { |
| 305 | + headers: { |
| 306 | + Cookie: cookies2, |
| 307 | + }, |
| 308 | + withCredentials: true, |
| 309 | + maxRedirects: 0, // Prevent axios from following redirects |
| 310 | + validateStatus: (status) => status >= 200 && status < 400, // Accept 3xx status codes |
| 311 | + }); |
| 312 | + const setCookieHeader = response.headers['set-cookie']; |
| 313 | + if (setCookieHeader) { |
| 314 | + // Find the 'sid' cookie in the set-cookie header |
| 315 | + const sidCookie = setCookieHeader.find((cookieStr: string) => cookieStr.startsWith('sid=')); |
| 316 | + if (sidCookie) { |
| 317 | + // Extract the sid value from the set-cookie string |
| 318 | + const sidMatch = sidCookie.match(/sid=([^;]+)/); |
| 319 | + if (sidMatch?.[1]) { |
| 320 | + const sidToken = sidMatch[1]; |
| 321 | + return sidToken; |
| 322 | + } |
| 323 | + } |
| 324 | + } |
| 325 | + } |
| 326 | + |
| 327 | + // if we can't establish a valid session this way, lets just warn the user and utilize the guest user context for the site |
| 328 | + // eslint-disable-next-line no-console |
| 329 | + console.warn( |
| 330 | + `Warning: could not establish valid auth token for your site '${this.siteDisplayName}'.` + |
| 331 | + 'Local Dev proxied requests to your site may fail or return data from the guest user context.' |
| 332 | + ); |
| 333 | + |
| 334 | + return ''; // Site will be guest user access only |
| 335 | + } |
| 336 | + |
| 337 | + // Not sure what scenarios we don't have an access token at all, but lets output a separate message here so we can distinguish these edge cases |
| 338 | + // eslint-disable-next-line no-console |
| 339 | + console.warn( |
| 340 | + 'Warning: sf cli org connection missing accessToken. Local Dev proxied requests to your site may fail or return data from the guest user context.' |
| 341 | + ); |
| 342 | + return ''; |
| 343 | + } |
228 | 344 | }
|
229 | 345 |
|
230 | 346 | /**
|
|
0 commit comments