@speedkit/cli 4.43.0-beta.1 → 4.43.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.
Files changed (109) hide show
  1. package/CHANGELOG.md +9 -2
  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/models/files.d.ts +0 -1
  6. package/dist/models/files.js +0 -1
  7. package/dist/services/bundler/bundle-service-factory.d.ts +1 -6
  8. package/dist/services/bundler/bundle-service-factory.js +2 -9
  9. package/dist/services/bundler/bundle-service.d.ts +1 -10
  10. package/dist/services/bundler/bundle-service.js +1 -16
  11. package/dist/services/bundler/index.d.ts +0 -1
  12. package/dist/services/bundler/index.js +0 -1
  13. package/dist/services/cli/cli-environment.js +0 -1
  14. package/dist/services/cli/cli-settings.d.ts +0 -5
  15. package/dist/services/cli/cli-settings.js +0 -1
  16. package/dist/services/deploy/checks/activation/customer-approval-check.js +1 -1
  17. package/dist/services/deploy/checks/post-deploy/refresh-deployment-job-check.d.ts +2 -2
  18. package/dist/services/deploy/checks/post-deploy/refresh-deployment-job-check.js +8 -7
  19. package/dist/services/deploy/checks/post-deploy/revalidated-module-check.d.ts +2 -2
  20. package/dist/services/deploy/checks/post-deploy/revalidated-module-check.js +11 -7
  21. package/dist/services/deploy/checks/post-deploy/save-files-check.d.ts +2 -2
  22. package/dist/services/deploy/checks/post-deploy/save-files-check.js +3 -2
  23. package/dist/services/deploy/checks/pre-deploy/device-detection-changed-check.js +3 -2
  24. package/dist/services/deploy/checks/pre-deploy/split-change-check.js +3 -2
  25. package/dist/services/deploy/deploy-service-factory.js +1 -3
  26. package/dist/services/deploy/deploy-service-model.d.ts +11 -1
  27. package/dist/services/deploy/deploy-service.d.ts +2 -0
  28. package/dist/services/deploy/deploy-service.js +26 -1
  29. package/dist/services/deploy/mr/merge-request-deploy-service-factory.js +1 -1
  30. package/dist/services/deploy/policy/deploy-policy-model.d.ts +1 -5
  31. package/dist/services/deploy/policy/deploy-policy-model.js +0 -4
  32. package/dist/services/deploy/spec/checks/post-deploy/refresh-deployment-job-check.spec.js +5 -12
  33. package/dist/services/deploy/spec/deploy-service.spec.js +64 -0
  34. package/dist/services/deploy/spec/policy/auto-deploy-policy.spec.js +0 -2
  35. package/dist/services/document-handler-runtime/document-handler-runtime-model.d.ts +0 -2
  36. package/dist/services/document-handler-runtime/document-handler-runtime-model.js +0 -2
  37. package/dist/services/document-handler-runtime/document-handler-server.d.ts +0 -17
  38. package/dist/services/document-handler-runtime/document-handler-server.js +20 -82
  39. package/dist/services/document-handler-runtime/factory/document-handler-runtime-service-factory.js +1 -1
  40. package/dist/services/integration-api/integration-api-factory.js +1 -1
  41. package/dist/services/integration-api/integration-api-model.d.ts +1 -2
  42. package/dist/services/integration-api/spec/speed-kit-config-file.spec.js +8 -70
  43. package/dist/services/integration-api/struct/customer-config.d.ts +1 -19
  44. package/dist/services/integration-api/struct/customer-config.js +3 -11
  45. package/dist/services/integration-api/struct/speed-kit-config-file.d.ts +4 -9
  46. package/dist/services/integration-api/struct/speed-kit-config-file.js +10 -30
  47. package/dist/services/onboarding/config-renderer/speed-kit-install-context.js +8 -24
  48. package/dist/services/onboarding/error/inject-installation-error.d.ts +6 -0
  49. package/dist/services/onboarding/error/inject-installation-error.js +11 -0
  50. package/dist/services/onboarding/error/inject-target-error.d.ts +6 -0
  51. package/dist/services/onboarding/error/inject-target-error.js +11 -0
  52. package/dist/services/onboarding/error/missing-customer-path-error.d.ts +1 -1
  53. package/dist/services/onboarding/error/missing-customer-path-error.js +2 -1
  54. package/dist/services/onboarding/fetch-events/customer-domain-document-response.d.ts +4 -14
  55. package/dist/services/onboarding/fetch-events/customer-domain-document-response.js +6 -45
  56. package/dist/services/onboarding/fetch-events/document-rewrite.d.ts +19 -0
  57. package/dist/services/onboarding/fetch-events/document-rewrite.js +47 -0
  58. package/dist/services/onboarding/fetch-events/speed-kit-install-html.d.ts +5 -1
  59. package/dist/services/onboarding/fetch-events/speed-kit-install-html.js +7 -2
  60. package/dist/services/onboarding/html-rewrites.d.ts +3 -3
  61. package/dist/services/onboarding/html-rewrites.js +3 -3
  62. package/dist/services/onboarding/index.d.ts +1 -1
  63. package/dist/services/onboarding/index.js +1 -1
  64. package/dist/services/onboarding/inject/content-security-policy.d.ts +14 -0
  65. package/dist/services/onboarding/inject/content-security-policy.js +54 -0
  66. package/dist/services/onboarding/inject/deployed-installation.d.ts +15 -0
  67. package/dist/services/onboarding/inject/deployed-installation.js +32 -0
  68. package/dist/services/onboarding/inject/foreign-install-request.d.ts +27 -0
  69. package/dist/services/onboarding/inject/foreign-install-request.js +50 -0
  70. package/dist/services/onboarding/inject/inject-document-rewrite.d.ts +23 -0
  71. package/dist/services/onboarding/inject/inject-document-rewrite.js +52 -0
  72. package/dist/services/onboarding/inject/inject-service.d.ts +32 -0
  73. package/dist/services/onboarding/inject/inject-service.js +72 -0
  74. package/dist/services/onboarding/inject/injected-installation.d.ts +29 -0
  75. package/dist/services/onboarding/inject/injected-installation.js +37 -0
  76. package/dist/services/onboarding/onboarding-service-build-context.d.ts +15 -1
  77. package/dist/services/onboarding/onboarding-service-build-context.js +31 -2
  78. package/dist/services/onboarding/onboarding-service-factory.d.ts +23 -5
  79. package/dist/services/onboarding/onboarding-service-factory.js +87 -7
  80. package/dist/services/onboarding/spec/inject/content-security-policy.spec.d.ts +1 -0
  81. package/dist/services/onboarding/spec/inject/content-security-policy.spec.js +47 -0
  82. package/dist/services/onboarding/spec/inject/deployed-installation.spec.d.ts +1 -0
  83. package/dist/services/onboarding/spec/inject/deployed-installation.spec.js +49 -0
  84. package/dist/services/onboarding/spec/inject/foreign-install-request.spec.d.ts +1 -0
  85. package/dist/services/onboarding/spec/inject/foreign-install-request.spec.js +47 -0
  86. package/dist/services/onboarding/spec/inject/inject-document-rewrite.spec.d.ts +1 -0
  87. package/dist/services/onboarding/spec/inject/inject-document-rewrite.spec.js +66 -0
  88. package/dist/services/onboarding/spec/inject/injected-installation.spec.d.ts +1 -0
  89. package/dist/services/onboarding/spec/inject/injected-installation.spec.js +24 -0
  90. package/dist/services/onboarding/spec/onboarding-service-build-context.spec.d.ts +1 -0
  91. package/dist/services/onboarding/spec/onboarding-service-build-context.spec.js +22 -0
  92. package/dist/services/onboarding/spec/onboarding-service-factory.spec.js +53 -2
  93. package/dist/services/onboarding/templates/install-speed-kit-html-template.js +3 -0
  94. package/dist/services/onboarding/templates/install-speed-kit-js-template.js +0 -5
  95. package/dist/services/query-builder/query-builder-factory.js +3 -3
  96. package/oclif.manifest.json +26 -3
  97. package/package.json +1 -2
  98. package/dist/services/bundler/error/packjockel-error.d.ts +0 -3
  99. package/dist/services/bundler/error/packjockel-error.js +0 -3
  100. package/dist/services/bundler/packjockel-service.d.ts +0 -70
  101. package/dist/services/bundler/packjockel-service.js +0 -171
  102. package/dist/services/bundler/spec/packjockel-service.spec.js +0 -149
  103. package/dist/services/deploy/checks/post-deploy/deprecated-deployment-detection-check.d.ts +0 -15
  104. package/dist/services/deploy/checks/post-deploy/deprecated-deployment-detection-check.js +0 -70
  105. package/dist/services/deploy/error/check-module-file-error.d.ts +0 -4
  106. package/dist/services/deploy/error/check-module-file-error.js +0 -4
  107. package/dist/services/deploy/error/post-deploy-deployment-detection-error.d.ts +0 -4
  108. package/dist/services/deploy/error/post-deploy-deployment-detection-error.js +0 -4
  109. /package/dist/services/{bundler/spec/packjockel-service.spec.d.ts → deploy/spec/deploy-service.spec.d.ts} +0 -0
@@ -0,0 +1,52 @@
1
+ import { removeContentSecurityMetaTag, rewriteInstallResource, } from "../html-rewrites.js";
2
+ import { allowSource, allowSourceInMetaTags, } from "./content-security-policy.js";
3
+ const CSP_HEADER = "content-security-policy";
4
+ /**
5
+ * The rewrite of `--inject`: every document gets the install script of the deployed installation,
6
+ * and nothing of the local config.
7
+ */
8
+ export class InjectDocumentRewrite {
9
+ installation;
10
+ appOrigin;
11
+ removeContentSecurityPolicy;
12
+ cli;
13
+ reported = new Set();
14
+ constructor(installation,
15
+ /** The origin of the app, e.g. `https://example.app.baqend.com`. */
16
+ appOrigin, removeContentSecurityPolicy, cli) {
17
+ this.installation = installation;
18
+ this.appOrigin = appOrigin;
19
+ this.removeContentSecurityPolicy = removeContentSecurityPolicy;
20
+ this.cli = cli;
21
+ }
22
+ headers(headers) {
23
+ if (this.removeContentSecurityPolicy) {
24
+ return headers.filter((header) => !header.name.toLowerCase().includes(CSP_HEADER));
25
+ }
26
+ return headers.map((header) => {
27
+ // The report-only header blocks nothing, so it stays as the origin sent it.
28
+ if (header.name.toLowerCase() !== CSP_HEADER) {
29
+ return header;
30
+ }
31
+ const { policy, amended } = allowSource(header.value, this.appOrigin);
32
+ this.report(amended);
33
+ return { ...header, value: policy };
34
+ });
35
+ }
36
+ html(html) {
37
+ const injected = rewriteInstallResource(html, this.installation);
38
+ if (this.removeContentSecurityPolicy) {
39
+ return removeContentSecurityMetaTag(injected);
40
+ }
41
+ return allowSourceInMetaTags(injected, this.appOrigin, (amended) => this.report(amended));
42
+ }
43
+ /** Prints each distinct change once, not once per document. */
44
+ report(amended) {
45
+ const change = amended.join(", ");
46
+ if (!change || this.reported.has(change)) {
47
+ return;
48
+ }
49
+ this.reported.add(change);
50
+ this.cli.writeWarning(`Content Security Policy: added ${this.appOrigin} to ${change}. Pass -s to remove the policy instead.`);
51
+ }
52
+ }
@@ -0,0 +1,32 @@
1
+ import { CliServiceInterface } from "../../cli/index.js";
2
+ import { FetchEventHandler } from "../fetch-event-handler.js";
3
+ import { BrowserContext } from "../onboarding-model.js";
4
+ import { InjectedInstallation } from "./injected-installation.js";
5
+ export interface InjectServiceDeps {
6
+ readonly browserContext: BrowserContext;
7
+ readonly fetchEventHandler: FetchEventHandler;
8
+ readonly installation: InjectedInstallation;
9
+ /** The `scope` of `config_customer.json`: where the install page is served. */
10
+ readonly scope: string;
11
+ readonly cli: CliServiceInterface;
12
+ }
13
+ /**
14
+ * `sk onboarding --inject`: the site of a customer with a deployed installation injected, for a
15
+ * customer that has not installed Speed Kit.
16
+ *
17
+ * It launches the same Chrome as onboarding. The install script, the install page and the service
18
+ * worker wrapper come from the CLI. The config, the service worker and the documents come from the
19
+ * deployed installation, so the run needs no local config.
20
+ */
21
+ export declare class InjectService {
22
+ private readonly browserContext;
23
+ private readonly fetchEventHandler;
24
+ private readonly installation;
25
+ private readonly scope;
26
+ private readonly cli;
27
+ constructor(deps: InjectServiceDeps);
28
+ /** Installs Speed Kit through the install page, then blocks until the caller aborts `externalSignal` or Chrome disconnects. */
29
+ run(externalSignal: AbortSignal): Promise<void>;
30
+ private readyLine;
31
+ private findPage;
32
+ }
@@ -0,0 +1,72 @@
1
+ import { safe } from "../../../helpers/safe.js";
2
+ import { launchBrowser, resetBrowserState } from "../browser/launch-browser.js";
3
+ import { BROWSER_EVENTS } from "../onboarding-model.js";
4
+ import { waitForAbort } from "../onboarding-service.js";
5
+ /**
6
+ * `sk onboarding --inject`: the site of a customer with a deployed installation injected, for a
7
+ * customer that has not installed Speed Kit.
8
+ *
9
+ * It launches the same Chrome as onboarding. The install script, the install page and the service
10
+ * worker wrapper come from the CLI. The config, the service worker and the documents come from the
11
+ * deployed installation, so the run needs no local config.
12
+ */
13
+ export class InjectService {
14
+ browserContext;
15
+ fetchEventHandler;
16
+ installation;
17
+ scope;
18
+ cli;
19
+ constructor(deps) {
20
+ this.browserContext = deps.browserContext;
21
+ this.fetchEventHandler = deps.fetchEventHandler;
22
+ this.installation = deps.installation;
23
+ this.scope = deps.scope;
24
+ this.cli = deps.cli;
25
+ }
26
+ /** Installs Speed Kit through the install page, then blocks until the caller aborts `externalSignal` or Chrome disconnects. */
27
+ async run(externalSignal) {
28
+ this.cli.startAction("ONBOARDING:INJECT:BROWSER", `prepare browser ${this.cli.style.bold(this.browserContext.browserVersionString)}`);
29
+ const disconnected = new AbortController();
30
+ const shutdownSignal = AbortSignal.any([
31
+ externalSignal,
32
+ disconnected.signal,
33
+ ]);
34
+ const browser = await launchBrowser(this.browserContext);
35
+ for (const target of browser.targets()) {
36
+ if (target.type() === "browser") {
37
+ await this.fetchEventHandler.handleRequestFetchEvents(target);
38
+ }
39
+ }
40
+ browser.on(BROWSER_EVENTS.DISCONNECTED, () => {
41
+ this.cli.writeError("Browser disconnected, shutting down");
42
+ disconnected.abort();
43
+ });
44
+ const page = await this.findPage(browser);
45
+ const reset = await safe(page
46
+ .target()
47
+ .createCDPSession()
48
+ .then((session) => resetBrowserState(session, new URL(this.browserContext.domain).origin)));
49
+ if (reset.success !== true) {
50
+ this.cli.writeWarning(`Could not reset the browser state: ${reset.error}`);
51
+ }
52
+ this.cli.successAction("ONBOARDING:INJECT:BROWSER");
53
+ const url = new URL(this.installation.installPage(this.scope), this.browserContext.domain).href;
54
+ const navigation = await safe(page.goto(url));
55
+ if (navigation.success !== true) {
56
+ this.cli.writeWarning(`Could not open ${url}: ${navigation.error}`);
57
+ }
58
+ this.cli.writeSuccess(this.readyLine());
59
+ await waitForAbort(shutdownSignal);
60
+ await safe(browser.close());
61
+ }
62
+ readyLine() {
63
+ const installation = this.installation.testingId
64
+ ? `the testing installation ${this.installation.testingId}`
65
+ : "the latest deployed installation";
66
+ return `Injecting ${installation} into ${this.browserContext.domain}. It uses no local config file. Press Ctrl+C to stop.`;
67
+ }
68
+ async findPage(browser) {
69
+ const [page] = await browser.pages();
70
+ return page ?? browser.newPage();
71
+ }
72
+ }
@@ -0,0 +1,29 @@
1
+ /** The install script of a customer: `installPath` and `installParams` of `config_customer.json`. */
2
+ export interface InstallResource {
3
+ readonly installPath?: string;
4
+ readonly installParams?: string;
5
+ }
6
+ /**
7
+ * The deployed installation that `--inject` puts into the pages of the origin: the latest deployed
8
+ * one, or one testing installation.
9
+ */
10
+ export declare class InjectedInstallation implements InstallResource {
11
+ private readonly resource;
12
+ /** The id of a testing installation. Without one, the server resolves the installation that is live. */
13
+ readonly testingId?: string;
14
+ readonly installParams: string;
15
+ constructor(resource: InstallResource,
16
+ /** The id of a testing installation. Without one, the server resolves the installation that is live. */
17
+ testingId?: string);
18
+ /**
19
+ * The install resource. A testing installation carries `r=<id>`: the server then answers before
20
+ * a service worker is active, and for an app that has no live installation.
21
+ */
22
+ get installPath(): string;
23
+ /**
24
+ * The install page. `enableSpeedKit=1` puts the browser into group A of a split test, or no
25
+ * worker installs. `debugSpeedKit=<id>` makes the snippet keep the testing installation for the tab.
26
+ */
27
+ installPage(scope: string): string;
28
+ private withParam;
29
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * The deployed installation that `--inject` puts into the pages of the origin: the latest deployed
3
+ * one, or one testing installation.
4
+ */
5
+ export class InjectedInstallation {
6
+ resource;
7
+ testingId;
8
+ installParams;
9
+ constructor(resource,
10
+ /** The id of a testing installation. Without one, the server resolves the installation that is live. */
11
+ testingId) {
12
+ this.resource = resource;
13
+ this.testingId = testingId;
14
+ this.installParams = resource.installParams;
15
+ }
16
+ /**
17
+ * The install resource. A testing installation carries `r=<id>`: the server then answers before
18
+ * a service worker is active, and for an app that has no live installation.
19
+ */
20
+ get installPath() {
21
+ return this.withParam(this.resource.installPath, "r");
22
+ }
23
+ /**
24
+ * The install page. `enableSpeedKit=1` puts the browser into group A of a split test, or no
25
+ * worker installs. `debugSpeedKit=<id>` makes the snippet keep the testing installation for the tab.
26
+ */
27
+ installPage(scope) {
28
+ return this.withParam(`${scope}speed-kit-install.html?url=${encodeURIComponent(scope)}&enableSpeedKit=1`, "debugSpeedKit");
29
+ }
30
+ withParam(url, name) {
31
+ if (!this.testingId) {
32
+ return url;
33
+ }
34
+ const separator = url.includes("?") ? "&" : "?";
35
+ return `${url}${separator}${name}=${encodeURIComponent(this.testingId)}`;
36
+ }
37
+ }
@@ -1,5 +1,10 @@
1
1
  import { Interfaces } from "@oclif/core";
2
2
  import { CliEnvironment, CommandContextValues } from "../cli/index.js";
3
+ /**
4
+ * Gives a bare `--inject` its default value, because oclif knows no flag with an optional value.
5
+ * A value is the next argument, unless that argument is a flag.
6
+ */
7
+ export declare function withInjectDefault(argv: string[]): string[];
3
8
  declare const args: {
4
9
  customerPath: Interfaces.Arg<string, {
5
10
  exists?: boolean;
@@ -14,12 +19,14 @@ declare const flags: {
14
19
  ignoreContentSecurityPolicy: Interfaces.BooleanFlag<boolean>;
15
20
  headless: Interfaces.BooleanFlag<boolean>;
16
21
  browse: Interfaces.BooleanFlag<boolean>;
22
+ inject: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
23
+ app: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
17
24
  browserFetch: Interfaces.BooleanFlag<boolean>;
18
25
  useTestConfig: Interfaces.BooleanFlag<boolean>;
19
26
  configName: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
20
27
  };
21
28
  export interface OnboardingServiceBuildContextValues extends CommandContextValues {
22
- /** Missing only in browse mode. */
29
+ /** Optional in browse mode and in inject mode. */
23
30
  readonly customerPath?: string;
24
31
  readonly configName: string;
25
32
  readonly domain?: string;
@@ -33,6 +40,11 @@ export interface OnboardingServiceBuildContextValues extends CommandContextValue
33
40
  readonly debugPort: number;
34
41
  readonly browserFetch: boolean;
35
42
  readonly browse: boolean;
43
+ readonly inject: boolean;
44
+ /** The testing installation of `--inject <id>`. Without one, it injects the latest deployed installation. */
45
+ readonly testing?: string;
46
+ /** The app of `--inject`, when no customer config names it. */
47
+ readonly app?: string;
36
48
  }
37
49
  declare const OnboardingServiceBuildContext_base: new (values: OnboardingServiceBuildContextValues) => Readonly<OnboardingServiceBuildContextValues>;
38
50
  /** What `sk onboarding` starts: a local Speed Kit dev environment for one customer. */
@@ -51,6 +63,8 @@ export declare class OnboardingServiceBuildContext extends OnboardingServiceBuil
51
63
  ignoreContentSecurityPolicy: Interfaces.BooleanFlag<boolean>;
52
64
  headless: Interfaces.BooleanFlag<boolean>;
53
65
  browse: Interfaces.BooleanFlag<boolean>;
66
+ inject: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
67
+ app: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
54
68
  browserFetch: Interfaces.BooleanFlag<boolean>;
55
69
  useTestConfig: Interfaces.BooleanFlag<boolean>;
56
70
  configName: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
@@ -1,12 +1,27 @@
1
1
  import { Args, Flags } from "@oclif/core";
2
2
  import { CLI_CONFIG_IS_TEST, CLI_CONFIG_NAME, } from "../integration-api/customer-config-flags.js";
3
3
  import { Context } from "../../models/context.js";
4
+ /** The value `--inject` gets when it is passed without one. */
5
+ const LATEST_INSTALLATION = "latest";
6
+ /**
7
+ * Gives a bare `--inject` its default value, because oclif knows no flag with an optional value.
8
+ * A value is the next argument, unless that argument is a flag.
9
+ */
10
+ export function withInjectDefault(argv) {
11
+ return argv.map((argument, index) => {
12
+ const next = argv[index + 1];
13
+ const isBare = next === undefined || next.startsWith("-");
14
+ return argument === "--inject" && isBare
15
+ ? `--inject=${LATEST_INSTALLATION}`
16
+ : argument;
17
+ });
18
+ }
4
19
  const args = {
5
- // Optional for `--browse`, which analyses a site before its config exists; the factory requires it otherwise.
20
+ // Optional for `--browse` and `--inject`, which need no local config; the factory requires it otherwise.
6
21
  customerPath: Args.directory({
7
22
  name: "customerPath",
8
23
  required: false,
9
- description: "The customer config path (optional with --browse)",
24
+ description: "The customer config path (optional with --browse and --inject)",
10
25
  }),
11
26
  };
12
27
  const flags = {
@@ -53,6 +68,15 @@ const flags = {
53
68
  default: false,
54
69
  description: "Open the live site in the onboarding Chrome, with its extensions, but without request interception or Speed Kit injection. Takes the domain from -d or from the customer config.",
55
70
  }),
71
+ inject: Flags.string({
72
+ exclusive: ["browse"],
73
+ helpValue: "[<installationId>]",
74
+ description: "Inject a deployed Speed Kit installation into the site, for a customer that has not installed Speed Kit. Without a value it uses the latest deployed installation. With an id it uses that testing installation. Needs no local config: without a CUSTOMERPATH, pass --app and -d.",
75
+ }),
76
+ app: Flags.string({
77
+ dependsOn: ["inject"],
78
+ description: "The app of the installation that --inject uses. Wins over the app of the customer config.",
79
+ }),
56
80
  browserFetch: Flags.boolean({
57
81
  default: false,
58
82
  description: "Fetch every origin document with a second headless Chrome instead of a direct request. Only needed when bot protection refuses the CLI outright — a refusal is otherwise detected and rerouted on its own.",
@@ -77,6 +101,11 @@ export class OnboardingServiceBuildContext extends Context() {
77
101
  debugPort: parsedFlags.debugPort,
78
102
  browserFetch: parsedFlags.browserFetch,
79
103
  browse: parsedFlags.browse,
104
+ app: parsedFlags.app,
105
+ inject: parsedFlags.inject !== undefined,
106
+ testing: parsedFlags.inject === LATEST_INSTALLATION
107
+ ? undefined
108
+ : parsedFlags.inject,
80
109
  });
81
110
  }
82
111
  }
@@ -2,20 +2,38 @@ import { OnboardingServiceBuildContext } from "./onboarding-service-build-contex
2
2
  import { BrowserContext } from "./onboarding-model.js";
3
3
  import { OnboardingService } from "./onboarding-service.js";
4
4
  import { BrowseService } from "./browse/browse-service.js";
5
+ import { InjectService } from "./inject/inject-service.js";
6
+ import { DeployedInstallation } from "./inject/deployed-installation.js";
5
7
  import { BrowserExtensions } from "./browser/extension/extension-validator.js";
6
8
  export declare class OnboardingServiceFactory {
7
9
  private readonly context;
8
10
  constructor(context: OnboardingServiceBuildContext);
9
11
  /**
10
- * The service `sk onboarding` runs: the browse service under `--browse`, the onboarding service
11
- * otherwise.
12
+ * The service `sk onboarding` runs: the browse service under `--browse`, the inject service under
13
+ * `--inject`, the onboarding service otherwise.
12
14
  *
13
- * @throws {MissingCustomerPathError} Without `--browse` and without a CUSTOMERPATH.
15
+ * @throws {MissingCustomerPathError} Without `--browse`, without `--inject` and without a CUSTOMERPATH.
14
16
  */
15
- getService(): Promise<OnboardingService | BrowseService>;
17
+ getService(): Promise<OnboardingService | BrowseService | InjectService>;
18
+ /**
19
+ * The site with a deployed installation injected. It builds no install resource, no service
20
+ * worker and no documentHandler.
21
+ */
22
+ private getInjectService;
16
23
  /** The live site in the onboarding Chrome: the same launch, none of the interception. */
17
24
  private getBrowseService;
18
- /** Only config_customer.json: browse mode reads its domain and chromeFlags, nothing else. */
25
+ /**
26
+ * What inject mode injects, and where. The app and the domain come from the flags, else from a
27
+ * local `config_customer.json`. The service worker path and the scope come from the installation
28
+ * itself, so they are right for an installation that a local config does not describe.
29
+ *
30
+ * @throws {InjectTargetError} Without an app, or without a domain.
31
+ * @throws {InjectInstallationError} When the server has no installation for the domain.
32
+ */
33
+ private resolveInjectTarget;
34
+ /** The one request inject mode sends before Chrome starts. A spec replaces it. */
35
+ protected readDeployedInstallation(installPath: string, origin: string): Promise<DeployedInstallation>;
36
+ /** Only config_customer.json: browse mode and inject mode read nothing else. */
19
37
  private readCustomerConfig;
20
38
  /**
21
39
  * Resolves the extensions and the Chrome executable, then builds the launch. Onboarding and
@@ -6,13 +6,14 @@ import { BundleServiceFactory } from "../bundler/index.js";
6
6
  import { DiffServiceBuildContext, DiffServiceFactory } from "../diff/index.js";
7
7
  import { DocumentHandlerRuntimeServiceBuildContext } from "../document-handler-runtime/document-handler-runtime-service-build-context.js";
8
8
  import DocumentHandlerRuntimeServiceFactory from "../document-handler-runtime/factory/document-handler-runtime-service-factory.js";
9
- import { ExternalFileReader, IntegrationApiServiceBuildContext, VirtualFile, ExternalRecipe, IntegrationApiFactory, } from "../integration-api/index.js";
9
+ import { CustomerConfig, ExternalFileReader, IntegrationApiServiceBuildContext, VirtualFile, ExternalRecipe, IntegrationApiFactory, } from "../integration-api/index.js";
10
10
  import { InstallFileRecipe } from "./config-renderer/install-file-recipe.js";
11
11
  import { SpeedKitInstallContext } from "./config-renderer/speed-kit-install-context.js";
12
12
  import { Dashboard } from "./dashboard/index.js";
13
13
  import { RequestDiffService } from "./dashboard/request-diff-service.js";
14
14
  import { FetchEventHandler } from "./fetch-event-handler.js";
15
15
  import { CustomerDomainDocumentResponse } from "./fetch-events/customer-domain-document-response.js";
16
+ import { LocalDocumentRewrite } from "./fetch-events/document-rewrite.js";
16
17
  import { CustomerServiceWorkerJs } from "./fetch-events/customer-service-worker-js.js";
17
18
  import { DashboardRequest } from "./fetch-events/dashboard-request.js";
18
19
  import { SpeedKitAssetRequest } from "./fetch-events/speed-kit-asset-request.js";
@@ -25,6 +26,12 @@ import { BrowserContext, } from "./onboarding-model.js";
25
26
  import { OnboardingService } from "./onboarding-service.js";
26
27
  import { BrowseService } from "./browse/browse-service.js";
27
28
  import { resolveBrowseUrl } from "./browse/browse-url.js";
29
+ import { InjectDocumentRewrite } from "./inject/inject-document-rewrite.js";
30
+ import { InjectService } from "./inject/inject-service.js";
31
+ import { ForeignInstallRequest } from "./inject/foreign-install-request.js";
32
+ import { InjectedInstallation } from "./inject/injected-installation.js";
33
+ import { readDeployedInstallation, } from "./inject/deployed-installation.js";
34
+ import { InjectTargetError } from "./error/inject-target-error.js";
28
35
  import { MissingCustomerPathError } from "./error/missing-customer-path-error.js";
29
36
  import { Cache } from "./request-cache/cache.js";
30
37
  import { InstallSpeedKitHtmlTemplate } from "./templates/install-speed-kit-html-template.js";
@@ -53,20 +60,49 @@ export class OnboardingServiceFactory {
53
60
  this.context = context;
54
61
  }
55
62
  /**
56
- * The service `sk onboarding` runs: the browse service under `--browse`, the onboarding service
57
- * otherwise.
63
+ * The service `sk onboarding` runs: the browse service under `--browse`, the inject service under
64
+ * `--inject`, the onboarding service otherwise.
58
65
  *
59
- * @throws {MissingCustomerPathError} Without `--browse` and without a CUSTOMERPATH.
66
+ * @throws {MissingCustomerPathError} Without `--browse`, without `--inject` and without a CUSTOMERPATH.
60
67
  */
61
68
  async getService() {
62
69
  if (this.context.browse) {
63
70
  return this.getBrowseService();
64
71
  }
72
+ if (this.context.inject) {
73
+ return this.getInjectService();
74
+ }
65
75
  if (!this.context.customerPath) {
66
76
  throw new MissingCustomerPathError();
67
77
  }
68
78
  return this.getOnboardingService();
69
79
  }
80
+ /**
81
+ * The site with a deployed installation injected. It builds no install resource, no service
82
+ * worker and no documentHandler.
83
+ */
84
+ async getInjectService() {
85
+ const cli = this.context.environment.cli;
86
+ const localConfig = this.context.customerPath
87
+ ? await this.readCustomerConfig()
88
+ : undefined;
89
+ applyOriginProxy(localConfig?.chromeFlags, cli);
90
+ const { customerConfig, installation, domainToStart } = await this.resolveInjectTarget(localConfig);
91
+ const { browserContext } = await this.prepareBrowser(domainToStart, customerConfig.chromeFlags);
92
+ const handlers = [
93
+ new ForeignInstallRequest(customerConfig.appDomain, cli, installation.testingId),
94
+ new CustomerDomainDocumentResponse(customerConfig, new InjectDocumentRewrite(installation, `https://${customerConfig.appDomain}`, this.context.ignoreContentSecurityPolicy, cli)),
95
+ new SpeedKitInstallHtml(customerConfig, browserContext, new InstallSpeedKitHtmlTemplate(), installation.installPath),
96
+ new CustomerServiceWorkerJs(customerConfig),
97
+ ];
98
+ return new InjectService({
99
+ browserContext,
100
+ fetchEventHandler: new FetchEventHandler(handlers, customerConfig, cli, this.getConfigApi(customerConfig.app)),
101
+ installation,
102
+ scope: customerConfig.scope,
103
+ cli,
104
+ });
105
+ }
70
106
  /** The live site in the onboarding Chrome: the same launch, none of the interception. */
71
107
  async getBrowseService() {
72
108
  const cli = this.context.environment.cli;
@@ -78,7 +114,51 @@ export class OnboardingServiceFactory {
78
114
  const { browserContext } = await this.prepareBrowser(url, customerConfig?.chromeFlags);
79
115
  return new BrowseService(browserContext, cli);
80
116
  }
81
- /** Only config_customer.json: browse mode reads its domain and chromeFlags, nothing else. */
117
+ /**
118
+ * What inject mode injects, and where. The app and the domain come from the flags, else from a
119
+ * local `config_customer.json`. The service worker path and the scope come from the installation
120
+ * itself, so they are right for an installation that a local config does not describe.
121
+ *
122
+ * @throws {InjectTargetError} Without an app, or without a domain.
123
+ * @throws {InjectInstallationError} When the server has no installation for the domain.
124
+ */
125
+ async resolveInjectTarget(localConfig) {
126
+ const app = this.context.app || localConfig?.app;
127
+ if (!app) {
128
+ throw new InjectTargetError("app");
129
+ }
130
+ if (!this.context.domain && !localConfig) {
131
+ throw new InjectTargetError("domain");
132
+ }
133
+ const domainToStart = resolveBrowseUrl(this.context.domain, localConfig);
134
+ const origin = new URL(domainToStart).origin;
135
+ // A local config for another app describes neither its install path nor its app domain.
136
+ const ownConfig = localConfig?.app === app ? localConfig : undefined;
137
+ const installation = new InjectedInstallation({
138
+ installPath: ownConfig?.installPath ??
139
+ `https://${app}.app.baqend.com/v1/speedkit/install.js`,
140
+ installParams: ownConfig?.installParams ?? 'async="" crossorigin="anonymous"',
141
+ }, this.context.testing);
142
+ const deployed = await this.readDeployedInstallation(installation.installPath, origin);
143
+ const origins = new Set([...(localConfig?.origins ?? []), origin]);
144
+ const customerConfig = CustomerConfig.createFrom({
145
+ app,
146
+ origins: [...origins],
147
+ domain: domainToStart,
148
+ swPath: deployed.swPath,
149
+ scope: deployed.scope,
150
+ appDomain: ownConfig?.appDomain,
151
+ installPath: installation.installPath,
152
+ installParams: installation.installParams,
153
+ chromeFlags: localConfig?.chromeFlags,
154
+ });
155
+ return { customerConfig, installation, domainToStart };
156
+ }
157
+ /** The one request inject mode sends before Chrome starts. A spec replaces it. */
158
+ readDeployedInstallation(installPath, origin) {
159
+ return readDeployedInstallation(installPath, origin);
160
+ }
161
+ /** Only config_customer.json: browse mode and inject mode read nothing else. */
82
162
  async readCustomerConfig() {
83
163
  const integrationApi = new IntegrationApiFactory(new IntegrationApiServiceBuildContext({
84
164
  environment: this.context.environment,
@@ -150,7 +230,7 @@ export class OnboardingServiceFactory {
150
230
  customerPath: this.context.customerPath,
151
231
  verboseLevel: this.context.verboseLevel,
152
232
  }), files).buildDocumentHandlerServer();
153
- const bundler = new BundleServiceFactory(this.context.customerPath, this.context.environment.settings.packjockelPath).buildService();
233
+ const bundler = new BundleServiceFactory(this.context.customerPath).buildService();
154
234
  const skTemplate = new InstallSpeedKitJsTemplate();
155
235
  const speedKitInstallContext = new SpeedKitInstallContext(customerConfig, this.context.configName, files, bundler, skTemplate);
156
236
  await this.buildInstallResource(speedKitInstallContext, files, cli);
@@ -246,7 +326,7 @@ export class OnboardingServiceFactory {
246
326
  })).getService();
247
327
  const requestDiffService = new RequestDiffService(DiffService, documentHandler, cli);
248
328
  const handlers = [
249
- new CustomerDomainDocumentResponse(customerConfig, files.getByName(INTEGRATION_FILES.CONFIG.DYNAMIC_BLOCKS), files.getByName(INTEGRATION_FILES.CONFIG.DYNAMIC_STYLES), this.context.ignoreContentSecurityPolicy),
329
+ new CustomerDomainDocumentResponse(customerConfig, new LocalDocumentRewrite(customerConfig, files.getByName(INTEGRATION_FILES.CONFIG.DYNAMIC_BLOCKS), files.getByName(INTEGRATION_FILES.CONFIG.DYNAMIC_STYLES), this.context.ignoreContentSecurityPolicy)),
250
330
  new SpeedKitInstallHtml(customerConfig, browserContext, new InstallSpeedKitHtmlTemplate()),
251
331
  new SpeedKitInstallJs(customerConfig, files.getByName(INTEGRATION_FILES.BUILD.INSTALL), cli),
252
332
  new CustomerServiceWorkerJs(customerConfig),
@@ -0,0 +1,47 @@
1
+ import { expect } from "chai";
2
+ import { describe, it } from "mocha";
3
+ import { allowSource, allowSourceInMetaTags, } from "../../inject/content-security-policy.js";
4
+ const APP = "https://example.app.baqend.com";
5
+ describe("allowSource", () => {
6
+ it("adds the source to script-src and connect-src", () => {
7
+ const result = allowSource("script-src 'self' 'nonce-abc'; connect-src 'self'; img-src *", APP);
8
+ expect(result.policy).to.equal(`script-src 'self' 'nonce-abc' ${APP}; connect-src 'self' ${APP}; img-src *`);
9
+ expect(result.amended).to.deep.equal(["script-src", "connect-src"]);
10
+ });
11
+ it("creates a missing directive from default-src", () => {
12
+ const result = allowSource("default-src 'self'; script-src 'self'", APP);
13
+ expect(result.policy).to.equal(`default-src 'self'; script-src 'self' ${APP}; connect-src 'self' ${APP}`);
14
+ expect(result.amended).to.deep.equal(["script-src", "connect-src"]);
15
+ });
16
+ it("leaves a missing directive out when no default-src restricts it", () => {
17
+ const result = allowSource("script-src 'self'", APP);
18
+ expect(result.policy).to.equal(`script-src 'self' ${APP}`);
19
+ expect(result.amended).to.deep.equal(["script-src"]);
20
+ });
21
+ it("replaces 'none', which allows no second source", () => {
22
+ const result = allowSource("default-src 'none'", APP);
23
+ expect(result.policy).to.equal(`default-src 'none'; script-src ${APP}; connect-src ${APP}`);
24
+ });
25
+ it("adds the source to script-src-elem, which overrides script-src", () => {
26
+ const result = allowSource("script-src 'self'; script-src-elem 'self'", APP);
27
+ expect(result.policy).to.equal(`script-src 'self' ${APP}; script-src-elem 'self' ${APP}`);
28
+ });
29
+ it("reports nothing when the policy allows the source already", () => {
30
+ const policy = `script-src 'self' ${APP}; connect-src ${APP}`;
31
+ const result = allowSource(policy, APP);
32
+ expect(result.policy).to.equal(policy);
33
+ expect(result.amended).to.deep.equal([]);
34
+ });
35
+ });
36
+ describe("allowSourceInMetaTags", () => {
37
+ it("amends the policy of a meta tag and reports the directives", () => {
38
+ const amended = [];
39
+ const html = allowSourceInMetaTags(`<head><meta http-equiv="Content-Security-Policy" content="script-src 'self'"></head>`, APP, (directives) => amended.push(directives));
40
+ expect(html).to.equal(`<head><meta http-equiv="Content-Security-Policy" content="script-src 'self' ${APP}"></head>`);
41
+ expect(amended).to.deep.equal([["script-src"]]);
42
+ });
43
+ it("leaves HTML without a policy unchanged", () => {
44
+ const html = `<head><meta charset="utf-8"></head>`;
45
+ expect(allowSourceInMetaTags(html, APP, () => undefined)).to.equal(html);
46
+ });
47
+ });
@@ -0,0 +1,49 @@
1
+ import { expect } from "chai";
2
+ import { describe, it } from "mocha";
3
+ import { InjectInstallationError } from "../../error/inject-installation-error.js";
4
+ import { parseInstallResource, readDeployedInstallation, } from "../../inject/deployed-installation.js";
5
+ const ORIGIN = "https://www.example.com";
6
+ const INSTALL = "https://example.app.baqend.com/v1/speedkit/install.js";
7
+ function answer(status, body = "") {
8
+ return async () => new Response(status === 204 ? null : body, { status });
9
+ }
10
+ describe("parseInstallResource", () => {
11
+ it("reads the service worker path without its query", () => {
12
+ expect(parseInstallResource(`var speedKit={appName:"example",sw:"/apps/speed-kit/sw.js?r=abc&v=2.22.5",split:0};`, ORIGIN)).to.deep.equal({ swPath: "/apps/speed-kit/sw.js", scope: "/" });
13
+ });
14
+ it("reads the scope that the installation names", () => {
15
+ expect(parseInstallResource(`{sw:"/de/sw.js",scope:"/de/"}`, ORIGIN)).to.deep.equal({ swPath: "/de/sw.js", scope: "/de/" });
16
+ });
17
+ it("finds nothing in a resource without a service worker", () => {
18
+ expect(parseInstallResource("/* empty */", ORIGIN)).to.equal(undefined);
19
+ });
20
+ });
21
+ describe("readDeployedInstallation", () => {
22
+ it("fetches the install resource as a page of the origin", async () => {
23
+ const requests = [];
24
+ const fetchResource = (async (url, init) => {
25
+ requests.push({
26
+ url,
27
+ origin: init.headers.origin,
28
+ });
29
+ return new Response(`{sw:"/wrapper-sw.js?r=abc"}`);
30
+ });
31
+ const installation = await readDeployedInstallation(`${INSTALL}?r=abc`, ORIGIN, fetchResource);
32
+ expect(installation).to.deep.equal({
33
+ swPath: "/wrapper-sw.js",
34
+ scope: "/",
35
+ });
36
+ expect(requests).to.deep.equal([
37
+ { url: `${INSTALL}?r=abc`, origin: ORIGIN },
38
+ ]);
39
+ });
40
+ it("fails when the origin has no live installation", async () => {
41
+ const error = await readDeployedInstallation(INSTALL, ORIGIN, answer(204)).catch((error_) => error_);
42
+ expect(error).to.be.instanceOf(InjectInstallationError);
43
+ expect(error.message).to.contain("204");
44
+ });
45
+ it("fails when the install resource names no service worker", async () => {
46
+ const error = await readDeployedInstallation(INSTALL, ORIGIN, answer(200, "/* empty */")).catch((error_) => error_);
47
+ expect(error).to.be.instanceOf(InjectInstallationError);
48
+ });
49
+ });