@speedkit/cli 4.42.0 → 4.43.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +12 -2
  3. package/dist/commands/onboarding.d.ts +3 -0
  4. package/dist/commands/onboarding.js +7 -1
  5. package/dist/services/onboarding/error/inject-installation-error.d.ts +6 -0
  6. package/dist/services/onboarding/error/inject-installation-error.js +11 -0
  7. package/dist/services/onboarding/error/inject-target-error.d.ts +6 -0
  8. package/dist/services/onboarding/error/inject-target-error.js +11 -0
  9. package/dist/services/onboarding/error/missing-customer-path-error.d.ts +1 -1
  10. package/dist/services/onboarding/error/missing-customer-path-error.js +2 -1
  11. package/dist/services/onboarding/fetch-events/customer-domain-document-response.d.ts +4 -14
  12. package/dist/services/onboarding/fetch-events/customer-domain-document-response.js +6 -45
  13. package/dist/services/onboarding/fetch-events/document-rewrite.d.ts +19 -0
  14. package/dist/services/onboarding/fetch-events/document-rewrite.js +47 -0
  15. package/dist/services/onboarding/fetch-events/speed-kit-install-html.d.ts +5 -1
  16. package/dist/services/onboarding/fetch-events/speed-kit-install-html.js +7 -2
  17. package/dist/services/onboarding/html-rewrites.d.ts +3 -3
  18. package/dist/services/onboarding/html-rewrites.js +3 -3
  19. package/dist/services/onboarding/index.d.ts +1 -1
  20. package/dist/services/onboarding/index.js +1 -1
  21. package/dist/services/onboarding/inject/content-security-policy.d.ts +14 -0
  22. package/dist/services/onboarding/inject/content-security-policy.js +54 -0
  23. package/dist/services/onboarding/inject/deployed-installation.d.ts +15 -0
  24. package/dist/services/onboarding/inject/deployed-installation.js +32 -0
  25. package/dist/services/onboarding/inject/foreign-install-request.d.ts +27 -0
  26. package/dist/services/onboarding/inject/foreign-install-request.js +50 -0
  27. package/dist/services/onboarding/inject/inject-document-rewrite.d.ts +23 -0
  28. package/dist/services/onboarding/inject/inject-document-rewrite.js +52 -0
  29. package/dist/services/onboarding/inject/inject-service.d.ts +32 -0
  30. package/dist/services/onboarding/inject/inject-service.js +72 -0
  31. package/dist/services/onboarding/inject/injected-installation.d.ts +29 -0
  32. package/dist/services/onboarding/inject/injected-installation.js +37 -0
  33. package/dist/services/onboarding/onboarding-service-build-context.d.ts +15 -1
  34. package/dist/services/onboarding/onboarding-service-build-context.js +31 -2
  35. package/dist/services/onboarding/onboarding-service-factory.d.ts +23 -5
  36. package/dist/services/onboarding/onboarding-service-factory.js +86 -6
  37. package/dist/services/onboarding/spec/inject/content-security-policy.spec.d.ts +1 -0
  38. package/dist/services/onboarding/spec/inject/content-security-policy.spec.js +47 -0
  39. package/dist/services/onboarding/spec/inject/deployed-installation.spec.d.ts +1 -0
  40. package/dist/services/onboarding/spec/inject/deployed-installation.spec.js +49 -0
  41. package/dist/services/onboarding/spec/inject/foreign-install-request.spec.d.ts +1 -0
  42. package/dist/services/onboarding/spec/inject/foreign-install-request.spec.js +47 -0
  43. package/dist/services/onboarding/spec/inject/inject-document-rewrite.spec.d.ts +1 -0
  44. package/dist/services/onboarding/spec/inject/inject-document-rewrite.spec.js +66 -0
  45. package/dist/services/onboarding/spec/inject/injected-installation.spec.d.ts +1 -0
  46. package/dist/services/onboarding/spec/inject/injected-installation.spec.js +24 -0
  47. package/dist/services/onboarding/spec/onboarding-service-build-context.spec.d.ts +1 -0
  48. package/dist/services/onboarding/spec/onboarding-service-build-context.spec.js +22 -0
  49. package/dist/services/onboarding/spec/onboarding-service-factory.spec.js +53 -2
  50. package/dist/services/onboarding/templates/install-speed-kit-html-template.js +3 -0
  51. package/oclif.manifest.json +26 -3
  52. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,10 @@
1
+ # [4.43.0](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.42.0...v4.43.0) (2026-10-09)
2
+
3
+
4
+ ### Features
5
+
6
+ * **onboarding:** add --inject, a deployed installation on the real site ([fcc0a97](https://gitlab.orestes.info/baqend/speed-kit-cli/commit/fcc0a9708e3acdd3a32a2a96f4779c59534242c5))
7
+
1
8
  # [4.42.0](https://gitlab.orestes.info/baqend/speed-kit-cli/compare/v4.41.2...v4.42.0) (2026-10-07)
2
9
 
3
10
 
package/README.md CHANGED
@@ -728,10 +728,10 @@ Start a local dev environment for building and testing the Speed Kit configurati
728
728
  ```
729
729
  USAGE
730
730
  $ sk onboarding [CUSTOMERPATH] [-c <value>] [-t] [-d <value>] [-p] [--debugPort <value>] [-v] [-s]
731
- [--headless] [--browse] [--browserFetch]
731
+ [--headless] [--app <value> [--inject [<installationId>] | --browse]] [--browserFetch]
732
732
 
733
733
  ARGUMENTS
734
- [CUSTOMERPATH] The customer config path (optional with --browse)
734
+ [CUSTOMERPATH] The customer config path (optional with --browse and --inject)
735
735
 
736
736
  FLAGS
737
737
  -c, --configName=<value> [default: production] The costumer config name
@@ -740,6 +740,8 @@ FLAGS
740
740
  -s, --ignoreContentSecurityPolicy Removes header/meta "content-security-policy" for origin-responses
741
741
  -t, --useTestConfig Override app with configured testApp
742
742
  -v, --verboseLevel Show all messages
743
+ --app=<value> The app of the installation that --inject uses. Wins over the app of the customer
744
+ config.
743
745
  --browse Open the live site in the onboarding Chrome, with its extensions, but without
744
746
  request interception or Speed Kit injection. Takes the domain from -d or from the
745
747
  customer config.
@@ -750,6 +752,10 @@ FLAGS
750
752
  distinct ports to run multiple onboarding processes at once.
751
753
  --headless Run Chrome in headless mode (for CI environments). Implicitly enables remote
752
754
  debugging port.
755
+ --inject=[<installationId>] Inject a deployed Speed Kit installation into the site, for a customer that has not
756
+ installed Speed Kit. Without a value it uses the latest deployed installation. With
757
+ an id it uses that testing installation. Needs no local config: without a
758
+ CUSTOMERPATH, pass --app and -d.
753
759
 
754
760
  DESCRIPTION
755
761
  Start a local dev environment for building and testing the Speed Kit configuration
@@ -762,6 +768,10 @@ EXAMPLES
762
768
  $ sk onboarding --browse -d www.decathlon.de --headless --debugPort 9290
763
769
 
764
770
  $ sk onboarding customers/decathlon.de --browse -p
771
+
772
+ $ sk onboarding customers/decathlon.de --inject
773
+
774
+ $ sk onboarding customers/decathlon.de --inject <installationId>
765
775
  ```
766
776
 
767
777
  ## `sk origin-request CUSTOMERPATH PAGEURL`
@@ -17,11 +17,14 @@ export default class Onboarding extends SkCommand<OnboardingServiceBuildContext>
17
17
  ignoreContentSecurityPolicy: import("@oclif/core/interfaces").BooleanFlag<boolean>;
18
18
  headless: import("@oclif/core/interfaces").BooleanFlag<boolean>;
19
19
  browse: import("@oclif/core/interfaces").BooleanFlag<boolean>;
20
+ inject: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
21
+ app: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
20
22
  browserFetch: import("@oclif/core/interfaces").BooleanFlag<boolean>;
21
23
  useTestConfig: import("@oclif/core/interfaces").BooleanFlag<boolean>;
22
24
  configName: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
23
25
  };
24
26
  static examples: string[];
27
+ init(): Promise<void>;
25
28
  /** Onboarding runs the customer's documentHandler, with its node modules. */
26
29
  protected customerPathForModules(args: Record<string, unknown>): string | undefined;
27
30
  run(): Promise<void>;
@@ -1,5 +1,5 @@
1
1
  import { SkCommand } from "../base/sk-command.js";
2
- import { OnboardingServiceBuildContext, OnboardingServiceFactory, } from "../services/onboarding/index.js";
2
+ import { OnboardingServiceBuildContext, OnboardingServiceFactory, withInjectDefault, } from "../services/onboarding/index.js";
3
3
  export default class Onboarding extends SkCommand {
4
4
  static description = "Start a local dev environment for building and testing the Speed Kit configuration";
5
5
  static buildContext = OnboardingServiceBuildContext;
@@ -10,7 +10,13 @@ export default class Onboarding extends SkCommand {
10
10
  `$ sk onboarding customers/decathlon.de -c production -d www.decathlon.de`,
11
11
  `$ sk onboarding --browse -d www.decathlon.de --headless --debugPort 9290`,
12
12
  `$ sk onboarding customers/decathlon.de --browse -p`,
13
+ `$ sk onboarding customers/decathlon.de --inject`,
14
+ `$ sk onboarding customers/decathlon.de --inject <installationId>`,
13
15
  ];
16
+ async init() {
17
+ this.argv = withInjectDefault(this.argv);
18
+ await super.init();
19
+ }
14
20
  /** Onboarding runs the customer's documentHandler, with its node modules. */
15
21
  customerPathForModules(args) {
16
22
  return args.customerPath;
@@ -0,0 +1,6 @@
1
+ import ApplicationError from "../../error-handling/error/application-error.js";
2
+ /** The server has no installation that `sk onboarding --inject` can inject. */
3
+ export declare class InjectInstallationError extends ApplicationError {
4
+ readonly code = "INJECT_INSTALLATION_ERROR";
5
+ constructor(installUrl: string, reason: string);
6
+ }
@@ -0,0 +1,11 @@
1
+ import ApplicationError from "../../error-handling/error/application-error.js";
2
+ /** The server has no installation that `sk onboarding --inject` can inject. */
3
+ export class InjectInstallationError extends ApplicationError {
4
+ code = "INJECT_INSTALLATION_ERROR";
5
+ constructor(installUrl, reason) {
6
+ super(`No installation to inject at ${installUrl}: ${reason}.`, [
7
+ "check the app, the domain and the installation id",
8
+ "without an id the app needs a live installation for this domain: pass `--inject <installationId>` for a testing installation",
9
+ ]);
10
+ }
11
+ }
@@ -0,0 +1,6 @@
1
+ import ApplicationError from "../../error-handling/error/application-error.js";
2
+ /** `sk onboarding --inject` has no app, or no domain, to find the installation with. */
3
+ export declare class InjectTargetError extends ApplicationError {
4
+ readonly code = "INJECT_TARGET_ERROR";
5
+ constructor(missing: "app" | "domain");
6
+ }
@@ -0,0 +1,11 @@
1
+ import ApplicationError from "../../error-handling/error/application-error.js";
2
+ /** `sk onboarding --inject` has no app, or no domain, to find the installation with. */
3
+ export class InjectTargetError extends ApplicationError {
4
+ code = "INJECT_TARGET_ERROR";
5
+ constructor(missing) {
6
+ super(`Inject mode needs ${missing === "app" ? "an app" : "a domain"}.`, [
7
+ "pass both, e.g. `sk onboarding --inject --app example-shop -d www.example.com`",
8
+ "or pass a CUSTOMERPATH whose config_customer.json names them",
9
+ ]);
10
+ }
11
+ }
@@ -1,5 +1,5 @@
1
1
  import ApplicationError from "../../error-handling/error/application-error.js";
2
- /** `sk onboarding` without `--browse` runs a customer config, so it needs its directory. */
2
+ /** `sk onboarding` without `--browse` and without `--inject` runs a customer config, so it needs its directory. */
3
3
  export declare class MissingCustomerPathError extends ApplicationError {
4
4
  readonly code = "MISSING_CUSTOMER_PATH";
5
5
  constructor();
@@ -1,11 +1,12 @@
1
1
  import ApplicationError from "../../error-handling/error/application-error.js";
2
- /** `sk onboarding` without `--browse` runs a customer config, so it needs its directory. */
2
+ /** `sk onboarding` without `--browse` and without `--inject` runs a customer config, so it needs its directory. */
3
3
  export class MissingCustomerPathError extends ApplicationError {
4
4
  code = "MISSING_CUSTOMER_PATH";
5
5
  constructor() {
6
6
  super("Missing CUSTOMERPATH: onboarding needs a customer config.", [
7
7
  "pass the customer directory, e.g. `sk onboarding customers/example-shop`",
8
8
  "or add --browse to open the live site without a config",
9
+ "or add --inject with --app and -d to inject a deployed installation",
9
10
  ]);
10
11
  }
11
12
  }
@@ -1,30 +1,20 @@
1
1
  import { Protocol } from "devtools-protocol";
2
2
  import { FetchRequestPausedEventHandler } from "../onboarding-model.js";
3
- import { CustomerConfig, ConfigFileInterface } from "../../integration-api/index.js";
3
+ import { CustomerConfig } from "../../integration-api/index.js";
4
4
  import { CDPSession } from "puppeteer";
5
+ import { DocumentRewrite } from "./document-rewrite.js";
5
6
  /**
6
7
  * Intercepts any request to the customersOrigin and equivalent requests to baqendAssetApi
7
8
  * @implements {FetchRequestPausedEventHandler}
8
9
  */
9
10
  export declare class CustomerDomainDocumentResponse implements FetchRequestPausedEventHandler {
10
11
  private customerConfig;
11
- private configDynamicBlock;
12
- private configDynamicStyles;
13
- private removeContentSecurityPolicy;
12
+ private rewrite;
14
13
  get patterns(): Protocol.Fetch.RequestPattern[];
15
- constructor(customerConfig: CustomerConfig, configDynamicBlock: ConfigFileInterface, configDynamicStyles: ConfigFileInterface, removeContentSecurityPolicy: boolean);
14
+ constructor(customerConfig: CustomerConfig, rewrite: DocumentRewrite);
16
15
  handle(event: Protocol.Fetch.RequestPausedEvent, client: CDPSession): Promise<Partial<Protocol.Fetch.FulfillRequestRequest> | null>;
17
16
  private isValidHtmlContent;
18
17
  private isValidResponse;
19
18
  private isHtmlContentHeader;
20
19
  private getHtmlContent;
21
- private isSpeedKitResponse;
22
- private rewriteHtmlToLocalConfig;
23
- /**
24
- * Removes content policy headers from the given array of headers.
25
- *
26
- * @param {Protocol.Fetch.HeaderEntry[]} headers - The array of header entries.
27
- * @returns {Protocol.Fetch.HeaderEntry[]} - The modified array of header entries with content policy headers removed.
28
- */
29
- private removeContentSecurityHeaderFromResponse;
30
20
  }
@@ -1,6 +1,5 @@
1
1
  import { META_CONTENT_TYPE_REGEX, } from "../onboarding-model.js";
2
2
  import { OriginResponse } from "../browser/origin-response.js";
3
- import { removeContentSecurityMetaTag, rewriteInstallResource, } from "../html-rewrites.js";
4
3
  import iconv from "iconv-lite";
5
4
  import Encoding from "encoding-japanese";
6
5
  import { UnsupportedEncodingError } from "../error/unsupported-encoding-error.js";
@@ -10,9 +9,7 @@ import { UnsupportedEncodingError } from "../error/unsupported-encoding-error.js
10
9
  */
11
10
  export class CustomerDomainDocumentResponse {
12
11
  customerConfig;
13
- configDynamicBlock;
14
- configDynamicStyles;
15
- removeContentSecurityPolicy;
12
+ rewrite;
16
13
  get patterns() {
17
14
  const result = [];
18
15
  for (const origin of this.customerConfig.origins) {
@@ -47,11 +44,9 @@ export class CustomerDomainDocumentResponse {
47
44
  }
48
45
  return result;
49
46
  }
50
- constructor(customerConfig, configDynamicBlock, configDynamicStyles, removeContentSecurityPolicy) {
47
+ constructor(customerConfig, rewrite) {
51
48
  this.customerConfig = customerConfig;
52
- this.configDynamicBlock = configDynamicBlock;
53
- this.configDynamicStyles = configDynamicStyles;
54
- this.removeContentSecurityPolicy = removeContentSecurityPolicy;
49
+ this.rewrite = rewrite;
55
50
  }
56
51
  async handle(event, client) {
57
52
  if (!this.isValidResponse(event)) {
@@ -60,22 +55,12 @@ export class CustomerDomainDocumentResponse {
60
55
  if (!this.isHtmlContentHeader(event.responseHeaders)) {
61
56
  return;
62
57
  }
63
- let text = await this.getHtmlContent(client, event);
58
+ const text = await this.getHtmlContent(client, event);
64
59
  if (!this.isValidHtmlContent(text)) {
65
60
  return;
66
61
  }
67
- const headers = this.removeContentSecurityPolicy
68
- ? this.removeContentSecurityHeaderFromResponse(event.responseHeaders)
69
- : event.responseHeaders;
70
- if (this.customerConfig.forceInstall) {
71
- text = rewriteInstallResource(text, this.customerConfig);
72
- }
73
- if (this.isSpeedKitResponse(text)) {
74
- text = this.rewriteHtmlToLocalConfig(text);
75
- }
76
- const content = this.removeContentSecurityPolicy
77
- ? removeContentSecurityMetaTag(text)
78
- : text;
62
+ const headers = this.rewrite.headers(event.responseHeaders);
63
+ const content = this.rewrite.html(text);
79
64
  // replace origin contentTypeCharset with utf-8 as this is what it's converted to now
80
65
  let detectedEncoding = "utf-8";
81
66
  for (const header of headers) {
@@ -138,28 +123,4 @@ export class CustomerDomainDocumentResponse {
138
123
  }
139
124
  return body;
140
125
  }
141
- isSpeedKitResponse(text) {
142
- return text.includes("speed-kit-dynamic");
143
- }
144
- rewriteHtmlToLocalConfig(html) {
145
- const DF_CONFIG_PATTERN = /(<script[^>]* id="speed-kit-df-config"[^>]*>)([\S\s]*?)(<\/script>)/g;
146
- const DF_STYLES_PATTERN = /(<style[^>]* id="speed-kit-df-styles"[^>]*>)(?:(?!<\/style>)[\S\s])*(<\/style>)/g;
147
- html = html.replaceAll(DF_CONFIG_PATTERN, (_, tag, body, end) => {
148
- const injectedConfig = body.match(/window\.dynamicBlockConfig\.appName\s=.*$/s) ?? [""];
149
- return `${tag}${this.configDynamicBlock.getContent()}${injectedConfig[0]}${end}`;
150
- });
151
- html = html.replaceAll(DF_STYLES_PATTERN, (_, tag, end) => `${tag}${this.configDynamicStyles.getContent()}${end}`);
152
- return html;
153
- }
154
- /**
155
- * Removes content policy headers from the given array of headers.
156
- *
157
- * @param {Protocol.Fetch.HeaderEntry[]} headers - The array of header entries.
158
- * @returns {Protocol.Fetch.HeaderEntry[]} - The modified array of header entries with content policy headers removed.
159
- */
160
- removeContentSecurityHeaderFromResponse(headers) {
161
- return headers.filter((header) => {
162
- return !header.name.toLowerCase().includes("content-security-policy");
163
- });
164
- }
165
126
  }
@@ -0,0 +1,19 @@
1
+ import { Protocol } from "devtools-protocol";
2
+ import { ConfigFileInterface, CustomerConfig } from "../../integration-api/index.js";
3
+ /** What onboarding changes in an HTML document of the origin before Chrome gets it. */
4
+ export interface DocumentRewrite {
5
+ headers(headers: Protocol.Fetch.HeaderEntry[]): Protocol.Fetch.HeaderEntry[];
6
+ html(html: string): string;
7
+ }
8
+ /** The rewrite of a local run: the document gets the config that is on disk. */
9
+ export declare class LocalDocumentRewrite implements DocumentRewrite {
10
+ private customerConfig;
11
+ private configDynamicBlock;
12
+ private configDynamicStyles;
13
+ private removeContentSecurityPolicy;
14
+ constructor(customerConfig: CustomerConfig, configDynamicBlock: ConfigFileInterface, configDynamicStyles: ConfigFileInterface, removeContentSecurityPolicy: boolean);
15
+ headers(headers: Protocol.Fetch.HeaderEntry[]): Protocol.Fetch.HeaderEntry[];
16
+ html(html: string): string;
17
+ private isSpeedKitResponse;
18
+ private rewriteHtmlToLocalConfig;
19
+ }
@@ -0,0 +1,47 @@
1
+ import { removeContentSecurityMetaTag, rewriteInstallResource, } from "../html-rewrites.js";
2
+ /** The rewrite of a local run: the document gets the config that is on disk. */
3
+ export class LocalDocumentRewrite {
4
+ customerConfig;
5
+ configDynamicBlock;
6
+ configDynamicStyles;
7
+ removeContentSecurityPolicy;
8
+ constructor(customerConfig, configDynamicBlock, configDynamicStyles, removeContentSecurityPolicy) {
9
+ this.customerConfig = customerConfig;
10
+ this.configDynamicBlock = configDynamicBlock;
11
+ this.configDynamicStyles = configDynamicStyles;
12
+ this.removeContentSecurityPolicy = removeContentSecurityPolicy;
13
+ }
14
+ headers(headers) {
15
+ if (!this.removeContentSecurityPolicy) {
16
+ return headers;
17
+ }
18
+ return headers.filter((header) => {
19
+ return !header.name.toLowerCase().includes("content-security-policy");
20
+ });
21
+ }
22
+ html(html) {
23
+ let text = html;
24
+ if (this.customerConfig.forceInstall) {
25
+ text = rewriteInstallResource(text, this.customerConfig);
26
+ }
27
+ if (this.isSpeedKitResponse(text)) {
28
+ text = this.rewriteHtmlToLocalConfig(text);
29
+ }
30
+ return this.removeContentSecurityPolicy
31
+ ? removeContentSecurityMetaTag(text)
32
+ : text;
33
+ }
34
+ isSpeedKitResponse(text) {
35
+ return text.includes("speed-kit-dynamic");
36
+ }
37
+ rewriteHtmlToLocalConfig(html) {
38
+ const DF_CONFIG_PATTERN = /(<script[^>]* id="speed-kit-df-config"[^>]*>)([\S\s]*?)(<\/script>)/g;
39
+ const DF_STYLES_PATTERN = /(<style[^>]* id="speed-kit-df-styles"[^>]*>)(?:(?!<\/style>)[\S\s])*(<\/style>)/g;
40
+ html = html.replaceAll(DF_CONFIG_PATTERN, (_, tag, body, end) => {
41
+ const injectedConfig = body.match(/window\.dynamicBlockConfig\.appName\s=.*$/s) ?? [""];
42
+ return `${tag}${this.configDynamicBlock.getContent()}${injectedConfig[0]}${end}`;
43
+ });
44
+ html = html.replaceAll(DF_STYLES_PATTERN, (_, tag, end) => `${tag}${this.configDynamicStyles.getContent()}${end}`);
45
+ return html;
46
+ }
47
+ }
@@ -9,7 +9,11 @@ export declare class SpeedKitInstallHtml implements FetchRequestPausedEventHandl
9
9
  private customerConfig;
10
10
  private browserContext;
11
11
  private speedKitInstallHtmlTemplate;
12
+ /** The install resource of `--inject`. It loads as the snippet of a customer does, with CORS. */
13
+ private injectedInstallPath?;
12
14
  get patterns(): Protocol.Fetch.RequestPattern[];
13
- constructor(customerConfig: CustomerConfig, browserContext: BrowserContext, speedKitInstallHtmlTemplate: InstallSpeedKitHtmlTemplate);
15
+ constructor(customerConfig: CustomerConfig, browserContext: BrowserContext, speedKitInstallHtmlTemplate: InstallSpeedKitHtmlTemplate,
16
+ /** The install resource of `--inject`. It loads as the snippet of a customer does, with CORS. */
17
+ injectedInstallPath?: string);
14
18
  handle(): Promise<Partial<Protocol.Fetch.FulfillRequestRequest>>;
15
19
  }
@@ -6,6 +6,7 @@ export class SpeedKitInstallHtml {
6
6
  customerConfig;
7
7
  browserContext;
8
8
  speedKitInstallHtmlTemplate;
9
+ injectedInstallPath;
9
10
  get patterns() {
10
11
  const result = [];
11
12
  for (const origin of this.customerConfig.origins) {
@@ -30,14 +31,18 @@ export class SpeedKitInstallHtml {
30
31
  }
31
32
  return result;
32
33
  }
33
- constructor(customerConfig, browserContext, speedKitInstallHtmlTemplate) {
34
+ constructor(customerConfig, browserContext, speedKitInstallHtmlTemplate,
35
+ /** The install resource of `--inject`. It loads as the snippet of a customer does, with CORS. */
36
+ injectedInstallPath) {
34
37
  this.customerConfig = customerConfig;
35
38
  this.browserContext = browserContext;
36
39
  this.speedKitInstallHtmlTemplate = speedKitInstallHtmlTemplate;
40
+ this.injectedInstallPath = injectedInstallPath;
37
41
  }
38
42
  async handle() {
39
43
  return new BaqendResponse(this.speedKitInstallHtmlTemplate.render({
40
- installPath: this.customerConfig.installPath,
44
+ installPath: this.injectedInstallPath ?? this.customerConfig.installPath,
45
+ crossOrigin: Boolean(this.injectedInstallPath),
41
46
  domain: this.browserContext.domain,
42
47
  swPath: this.customerConfig.swPath,
43
48
  }));
@@ -1,4 +1,4 @@
1
- import { CustomerConfig } from "../integration-api/index.js";
1
+ import { InstallResource } from "./inject/injected-installation.js";
2
2
  /**
3
3
  * Injects the Speed Kit install script into the given HTML, after removing any
4
4
  * existing install snippet. The origin's script nonce is reused so a
@@ -6,10 +6,10 @@ import { CustomerConfig } from "../integration-api/index.js";
6
6
  * opening `<head>`, falling back to before the closing `</head>`.
7
7
  *
8
8
  * @param {string} text - the HTML to rewrite
9
- * @param {CustomerConfig} customerConfig - provides the install path/params
9
+ * @param {InstallResource} install - provides the install path/params
10
10
  * @returns {string} - the HTML with the install script injected
11
11
  */
12
- export declare function rewriteInstallResource(text: string, customerConfig: CustomerConfig): string;
12
+ export declare function rewriteInstallResource(text: string, install: InstallResource): string;
13
13
  /**
14
14
  * Removes the content security meta tag from the provided HTML content.
15
15
  *
@@ -6,15 +6,15 @@ import { SpeedKitInstallRegex } from "./onboarding-model.js";
6
6
  * opening `<head>`, falling back to before the closing `</head>`.
7
7
  *
8
8
  * @param {string} text - the HTML to rewrite
9
- * @param {CustomerConfig} customerConfig - provides the install path/params
9
+ * @param {InstallResource} install - provides the install path/params
10
10
  * @returns {string} - the HTML with the install script injected
11
11
  */
12
- export function rewriteInstallResource(text, customerConfig) {
12
+ export function rewriteInstallResource(text, install) {
13
13
  text = text.replace(SpeedKitInstallRegex, "");
14
14
  const matchOpeningHead = /<\s*head\b[^>]*>/;
15
15
  const matchClosingHead = /<\/\s*head\s*>/;
16
16
  const nonceMatch = text.match(/<script\s(?:[^>]*?\s)?nonce\s*=\s*["']?([^\s"'>]*)/i);
17
- const installScript = `<script ${nonceMatch ? 'nonce="' + nonceMatch[1] + '"' : ""} src="${customerConfig.installPath}" ${customerConfig.installParams}></script>`;
17
+ const installScript = `<script ${nonceMatch ? 'nonce="' + nonceMatch[1] + '"' : ""} src="${install.installPath}" ${install.installParams}></script>`;
18
18
  if (matchOpeningHead.test(text)) {
19
19
  return text.replace(matchOpeningHead, (head) => `${head}\n${installScript}`);
20
20
  }
@@ -1,3 +1,3 @@
1
- export { OnboardingServiceBuildContext } from "./onboarding-service-build-context.js";
1
+ export { OnboardingServiceBuildContext, withInjectDefault, } from "./onboarding-service-build-context.js";
2
2
  export * from "./onboarding-service.js";
3
3
  export * from "./onboarding-service-factory.js";
@@ -1,3 +1,3 @@
1
- export { OnboardingServiceBuildContext } from "./onboarding-service-build-context.js";
1
+ export { OnboardingServiceBuildContext, withInjectDefault, } from "./onboarding-service-build-context.js";
2
2
  export * from "./onboarding-service.js";
3
3
  export * from "./onboarding-service-factory.js";
@@ -0,0 +1,14 @@
1
+ export interface AmendedPolicy {
2
+ readonly policy: string;
3
+ /** The directives that gained `source`. Empty when the policy allowed it already. */
4
+ readonly amended: string[];
5
+ }
6
+ /**
7
+ * Allows `source` to load scripts and to be fetched under `policy`.
8
+ *
9
+ * A directive that is absent falls back to `default-src`, so it is created from `default-src`
10
+ * first. Without `default-src` an absent directive restricts nothing and stays absent.
11
+ */
12
+ export declare function allowSource(policy: string, source: string): AmendedPolicy;
13
+ /** Applies {@link allowSource} to every policy that the HTML sets in a meta tag. */
14
+ export declare function allowSourceInMetaTags(html: string, source: string, onAmended: (amended: string[]) => void): string;
@@ -0,0 +1,54 @@
1
+ /** The directives that fall back to `default-src` and that a script from another host needs. */
2
+ const FALLBACK_DIRECTIVES = ["script-src", "connect-src"];
3
+ const CSP_META = /(<meta[^>]*http-equiv=["']content-security-policy["'][^>]*content=")([^"]*)(")/gis;
4
+ /**
5
+ * Allows `source` to load scripts and to be fetched under `policy`.
6
+ *
7
+ * A directive that is absent falls back to `default-src`, so it is created from `default-src`
8
+ * first. Without `default-src` an absent directive restricts nothing and stays absent.
9
+ */
10
+ export function allowSource(policy, source) {
11
+ const directives = policy
12
+ .split(";")
13
+ .map((directive) => directive.trim())
14
+ .filter(Boolean)
15
+ .map((directive) => directive.split(/\s+/));
16
+ const find = (name) => directives.find(([directive]) => directive.toLowerCase() === name);
17
+ const amended = [];
18
+ const allow = (directive) => {
19
+ const sources = directive.slice(1).filter((entry) => entry !== "'none'");
20
+ if (sources.includes(source)) {
21
+ return;
22
+ }
23
+ directive.splice(1, Infinity, ...sources, source);
24
+ amended.push(directive[0]);
25
+ };
26
+ const fallback = find("default-src");
27
+ for (const name of FALLBACK_DIRECTIVES) {
28
+ let directive = find(name);
29
+ if (!directive && fallback) {
30
+ directive = [name, ...fallback.slice(1)];
31
+ directives.push(directive);
32
+ }
33
+ if (directive) {
34
+ allow(directive);
35
+ }
36
+ }
37
+ // It overrides script-src for a script element, so it needs the source too.
38
+ const scriptElement = find("script-src-elem");
39
+ if (scriptElement) {
40
+ allow(scriptElement);
41
+ }
42
+ return {
43
+ policy: directives.map((directive) => directive.join(" ")).join("; "),
44
+ amended,
45
+ };
46
+ }
47
+ /** Applies {@link allowSource} to every policy that the HTML sets in a meta tag. */
48
+ export function allowSourceInMetaTags(html, source, onAmended) {
49
+ return html.replaceAll(CSP_META, (_, open, policy, close) => {
50
+ const result = allowSource(policy, source);
51
+ onAmended(result.amended);
52
+ return `${open}${result.policy}${close}`;
53
+ });
54
+ }
@@ -0,0 +1,15 @@
1
+ /** What inject mode reads from the install resource of an installation, not from a local config. */
2
+ export interface DeployedInstallation {
3
+ /** Where the installation registers its service worker, e.g. `/wrapper-sw.js`. */
4
+ readonly swPath: string;
5
+ /** The scope of that service worker. `/` when the installation names none. */
6
+ readonly scope: string;
7
+ }
8
+ /** Reads the service worker path and the scope out of the config in an install resource. */
9
+ export declare function parseInstallResource(installJs: string, origin: string): DeployedInstallation | undefined;
10
+ /**
11
+ * Fetches the install resource as a page of `origin` does, and reads the installation from it.
12
+ *
13
+ * @throws {InjectInstallationError} When the server answers with no install resource for the origin.
14
+ */
15
+ export declare function readDeployedInstallation(installPath: string, origin: string, fetchResource?: typeof fetch): Promise<DeployedInstallation>;
@@ -0,0 +1,32 @@
1
+ import { InjectInstallationError } from "../error/inject-installation-error.js";
2
+ /** Reads the service worker path and the scope out of the config in an install resource. */
3
+ export function parseInstallResource(installJs, origin) {
4
+ const sw = /\bsw:\s*"([^"]+)"/.exec(installJs)?.[1];
5
+ if (!sw) {
6
+ return undefined;
7
+ }
8
+ const scope = /\bscope:\s*"([^"]+)"/.exec(installJs)?.[1];
9
+ return { swPath: new URL(sw, origin).pathname, scope: scope ?? "/" };
10
+ }
11
+ /**
12
+ * Fetches the install resource as a page of `origin` does, and reads the installation from it.
13
+ *
14
+ * @throws {InjectInstallationError} When the server answers with no install resource for the origin.
15
+ */
16
+ export async function readDeployedInstallation(installPath, origin, fetchResource = fetch) {
17
+ const installUrl = new URL(installPath, origin).href;
18
+ const response = await fetchResource(installUrl, {
19
+ headers: { origin },
20
+ }).catch((error) => {
21
+ throw new InjectInstallationError(installUrl, String(error));
22
+ });
23
+ // The server answers 204 when the origin has no live installation.
24
+ if (response.status !== 200) {
25
+ throw new InjectInstallationError(installUrl, `the server answered ${response.status}`);
26
+ }
27
+ const installation = parseInstallResource(await response.text(), origin);
28
+ if (!installation) {
29
+ throw new InjectInstallationError(installUrl, "the install resource names no service worker");
30
+ }
31
+ return installation;
32
+ }
@@ -0,0 +1,27 @@
1
+ import { Protocol } from "devtools-protocol";
2
+ import { CliServiceInterface } from "../../cli/index.js";
3
+ import { AbortResponse } from "../browser/abort-response.js";
4
+ import { FetchRequestPausedEventHandler } from "../onboarding-model.js";
5
+ /**
6
+ * Keeps every install resource out of the run, except the one that inject mode injects.
7
+ *
8
+ * An origin can carry an integration of its own: another app, or the live installation of the
9
+ * same app while a testing installation is injected. That install resource registers its own
10
+ * service worker on the same scope, which replaces the injected one.
11
+ */
12
+ export declare class ForeignInstallRequest implements FetchRequestPausedEventHandler {
13
+ /** The domain of the injected app, e.g. `example.app.baqend.com`. */
14
+ private readonly appDomain;
15
+ private readonly cli;
16
+ /** The injected testing installation. Without one, any installation of the app may load. */
17
+ private readonly testingId?;
18
+ readonly patterns: Protocol.Fetch.RequestPattern[];
19
+ private readonly reported;
20
+ constructor(
21
+ /** The domain of the injected app, e.g. `example.app.baqend.com`. */
22
+ appDomain: string, cli: CliServiceInterface,
23
+ /** The injected testing installation. Without one, any installation of the app may load. */
24
+ testingId?: string);
25
+ handle(event: Protocol.Fetch.RequestPausedEvent): Promise<AbortResponse | null>;
26
+ private isInjected;
27
+ }
@@ -0,0 +1,50 @@
1
+ import { AbortResponse } from "../browser/abort-response.js";
2
+ /**
3
+ * Keeps every install resource out of the run, except the one that inject mode injects.
4
+ *
5
+ * An origin can carry an integration of its own: another app, or the live installation of the
6
+ * same app while a testing installation is injected. That install resource registers its own
7
+ * service worker on the same scope, which replaces the injected one.
8
+ */
9
+ export class ForeignInstallRequest {
10
+ appDomain;
11
+ cli;
12
+ testingId;
13
+ // `FetchEventHandler` reads a pattern a second time as a regular expression, so it must be valid
14
+ // as both. `*.*` is "any host with a dot" for Chrome and "any characters" for the expression.
15
+ patterns = [
16
+ {
17
+ requestStage: "Request",
18
+ urlPattern: "https://*.*app.baqend.com/v1/speedkit/install*",
19
+ },
20
+ ];
21
+ reported = new Set();
22
+ constructor(
23
+ /** The domain of the injected app, e.g. `example.app.baqend.com`. */
24
+ appDomain, cli,
25
+ /** The injected testing installation. Without one, any installation of the app may load. */
26
+ testingId) {
27
+ this.appDomain = appDomain;
28
+ this.cli = cli;
29
+ this.testingId = testingId;
30
+ }
31
+ async handle(event) {
32
+ const url = new URL(event.request.url);
33
+ if (this.isInjected(url)) {
34
+ return null;
35
+ }
36
+ // Once per resource: a page requests it on every navigation.
37
+ const resource = `${url.host}${url.pathname}${url.search}`;
38
+ if (!this.reported.has(resource)) {
39
+ this.reported.add(resource);
40
+ this.cli.writeWarning(`Blocked the install resource ${url.href}: it is not the injected installation.`);
41
+ }
42
+ return new AbortResponse("BlockedByClient");
43
+ }
44
+ isInjected(url) {
45
+ if (url.host !== this.appDomain) {
46
+ return false;
47
+ }
48
+ return (!this.testingId || url.searchParams.getAll("r").includes(this.testingId));
49
+ }
50
+ }