@queue-it/fastly 1.0.4 → 2.0.0-beta.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.
@@ -1,10 +1,9 @@
1
- import { Fastly, Headers, Request } from "@fastly/as-compute";
2
1
  import { RequestLogger } from "./helper";
3
2
 
4
- export function getIntegrationConfig(
3
+ export async function getIntegrationConfig(
5
4
  details: IntegrationDetails,
6
5
  endpointProvider: IntegrationEndpointProvider
7
- ): string {
6
+ ): Promise<string> {
8
7
  const headers = new Headers();
9
8
  headers.set("api-key", details.apiKey);
10
9
  headers.set("host", endpointProvider.getHostname(details.customerId));
@@ -16,19 +15,16 @@ export function getIntegrationConfig(
16
15
  headers: headers,
17
16
  }
18
17
  );
19
- let cacheOverride = new Fastly.CacheOverride();
20
- let cacheConf = endpointProvider.getCacheConfig();
21
- if (cacheConf.maxAge != -1) {
22
- cacheOverride.setTTL(cacheConf.maxAge);
23
- }
24
- if (cacheConf.staleWhileRevalidate != -1) {
25
- cacheOverride.setSWR(cacheConf.staleWhileRevalidate);
26
- }
18
+ const cacheConf = endpointProvider.getCacheConfig();
19
+ const cacheInit: { ttl?: number; swr?: number } = {};
20
+ if (cacheConf.maxAge !== -1) cacheInit.ttl = cacheConf.maxAge;
21
+ if (cacheConf.staleWhileRevalidate !== -1) cacheInit.swr = cacheConf.staleWhileRevalidate;
22
+ const cacheOverride = new CacheOverride("override", cacheInit);
27
23
 
28
- let beresp = Fastly.fetch(request, {
24
+ const beresp = await fetch(request, {
29
25
  backend: details.queueItOrigin,
30
26
  cacheOverride: cacheOverride,
31
- }).wait();
27
+ });
32
28
 
33
29
  if (!(details.logger instanceof MockLogger)) {
34
30
  let cacheState = beresp.headers.get("x-cache");
@@ -41,7 +37,7 @@ export function getIntegrationConfig(
41
37
  if (beresp.status != 200) {
42
38
  return "";
43
39
  }
44
- return beresp.text();
40
+ return await beresp.text();
45
41
  }
46
42
 
47
43
  const integrationCustomerId = "customerId",
@@ -52,19 +48,20 @@ const integrationCustomerId = "customerId",
52
48
  workerHost = "workerHost";
53
49
 
54
50
  export function resolveIntegrationDetails(): IntegrationDetails | null {
55
- const dict = new Fastly.Dictionary(integrationDictionary);
51
+ const dict = new ConfigStore(integrationDictionary);
56
52
  if (
57
- !dict.contains(integrationCustomerId) ||
58
- !dict.contains(integrationApiKey) ||
59
- !dict.contains(integrationSecret) ||
60
- !dict.contains(integrationQueueItOrigin)
53
+ dict.get(integrationCustomerId) === null ||
54
+ dict.get(integrationApiKey) === null ||
55
+ dict.get(integrationSecret) === null ||
56
+ dict.get(integrationQueueItOrigin) === null
61
57
  ) {
62
58
  return null;
63
59
  }
64
60
 
65
61
  let workerHostValue = "";
66
- if (dict.contains(workerHost)) {
67
- workerHostValue = dict.get(workerHost)!;
62
+ const workerHostVal = dict.get(workerHost);
63
+ if (workerHostVal !== null) {
64
+ workerHostValue = workerHostVal;
68
65
  }
69
66
 
70
67
  return new IntegrationDetails(
@@ -77,8 +74,8 @@ export function resolveIntegrationDetails(): IntegrationDetails | null {
77
74
  }
78
75
 
79
76
  export class IntegrationEndpointCacheConfig {
80
- maxAge: i16 = -1;
81
- staleWhileRevalidate: i16 = -1;
77
+ maxAge: number = -1;
78
+ staleWhileRevalidate: number = -1;
82
79
  }
83
80
 
84
81
  export interface IntegrationEndpointProvider {
@@ -1,137 +1,131 @@
1
- import { Request, Response, Headers } from "@fastly/as-compute";
2
- import { KnownUser } from "./sdk/KnownUser";
3
- import { QueueITHelper } from "./helper";
4
- import { FastlyHttpContextProvider, getHttpHandler } from "./contextProvider";
5
- import {
6
- getIntegrationConfig,
7
- resolveIntegrationDetails,
8
- IntegrationDetails,
9
- QueueItIntegrationEndpointProvider,
10
- } from "./integrationConfigProvider";
11
- import { Utils } from "./sdk/QueueITHelpers";
12
-
13
- const QUEUEIT_FAILED_HEADERNAME = "x-queueit-failed";
14
- let httpProvider: FastlyHttpContextProvider | null = null;
15
-
16
- export function onQueueITRequest(
17
- req: Request,
18
- conf: IntegrationDetails | null = null
19
- ): Response | null {
20
- if (conf == null) {
21
- conf = resolveIntegrationDetails();
22
- }
23
- if (conf == null) {
24
- return new Response(String.UTF8.encode("No integration details found."), {
25
- headers: new Headers(),
26
- status: 404,
27
- url: "",
28
- });
29
- }
30
-
31
- const integrationProvider =
32
- conf.provider == null
33
- ? new QueueItIntegrationEndpointProvider()
34
- : conf.provider;
35
- QueueITHelper.configureKnownUserHashing();
36
- httpProvider = getHttpHandler(req);
37
-
38
- let integrationConfigJson = getIntegrationConfig(conf, integrationProvider);
39
- const requestUrl: string = conf.resolveWorkerRequestUrl(req.url);
40
-
41
- const queueItToken = Utils.getParameterByName(
42
- requestUrl,
43
- KnownUser.QueueITTokenKey
44
- );
45
- const requestUrlWithoutToken: string = Utils.removeQueueItToken(requestUrl);
46
-
47
- // The requestUrlWithoutToken is used to match Triggers and as the Target url (where to return the users to).
48
- // It is therefor important that this is exactly the url of the users browsers. So, if your webserver is
49
- // behind e.g. a load balancer that modifies the host name or port, reformat requestUrlWithoutToken before proceeding.
50
- const validationResultPair = KnownUser.validateRequestByIntegrationConfig(
51
- requestUrlWithoutToken,
52
- queueItToken,
53
- integrationConfigJson,
54
- conf.customerId,
55
- conf.secretKey,
56
- httpProvider!
57
- );
58
-
59
- if (
60
- validationResultPair.first != null &&
61
- validationResultPair.first!.doRedirect()
62
- ) {
63
- const validationResult = validationResultPair.first!;
64
-
65
- if (validationResult.isAjaxResult) {
66
- let response = new Response(null, {
67
- status: 200,
68
- headers: httpProvider!.getHttpResponse().getHeaders(),
69
- url: "",
70
- });
71
- // In case of ajax call send the user to the queue by sending a custom queue-it header and redirecting user to queue from javascript
72
- response.headers.set("Access-Control-Expose-Headers", validationResult.getAjaxQueueRedirectHeaderKey());
73
- response.headers.set(
74
- validationResult.getAjaxQueueRedirectHeaderKey(),
75
- QueueITHelper.addKUPlatformVersion(
76
- validationResult.getAjaxRedirectUrl()
77
- )
78
- );
79
- Utils.addNoCacheHeaders(response);
80
- return response;
81
- } else {
82
- let response = new Response(null, {
83
- status: 302,
84
- headers: httpProvider!.getHttpResponse().getHeaders(),
85
- url: "",
86
- });
87
- // Send the user to the queue - either because hash was missing or because is was invalid
88
- response.headers.set(
89
- "Location",
90
- QueueITHelper.addKUPlatformVersion(validationResult.redirectUrl)
91
- );
92
- Utils.addNoCacheHeaders(response);
93
- return response;
94
- }
95
- } else if (validationResultPair.first != null) {
96
- const validationResult = validationResultPair.first!;
97
- // Request can continue - we remove queueittoken form querystring parameter to avoid sharing of user specific token
98
- // Support mobile scenario adding the condition !validationResult.isAjaxResult
99
- if (
100
- queueItToken != "" &&
101
- !validationResult.isAjaxResult &&
102
- validationResult.actionType == "Queue"
103
- ) {
104
- let response = new Response(null, {
105
- status: 302,
106
- headers: httpProvider!.getHttpResponse().getHeaders(),
107
- url: requestUrlWithoutToken,
108
- });
109
- response.headers.set("Location", requestUrlWithoutToken);
110
- Utils.addNoCacheHeaders(response);
111
- return response;
112
- } else {
113
- // lets caller decide the next step, or just serve the request normally
114
- return null;
115
- }
116
- } else if (validationResultPair.second != null) {
117
- httpProvider!.isError = true;
118
- }
119
-
120
- return null;
121
- }
122
-
123
- //Fill in the Queue-it headers
124
- export function onQueueITResponse(res: Response): void {
125
- const contextHeaders = httpProvider!.getHttpResponse().getHeaders();
126
- const contextHeaderKeys = contextHeaders.keys();
127
-
128
- if (httpProvider!.isError) {
129
- res.headers.append(QUEUEIT_FAILED_HEADERNAME, "true");
130
- }
131
- for (let i = 0; i < contextHeaderKeys.length; i++) {
132
- if (contextHeaderKeys[i].length == 0) continue;
133
- let value = contextHeaders.get(contextHeaderKeys[i]);
134
- if (value != null && value!.length > 0)
135
- res.headers.append(contextHeaderKeys[i], value!);
136
- }
137
- }
1
+ import { KnownUser } from "./sdk/KnownUser";
2
+ import { QueueITHelper } from "./helper";
3
+ import { FastlyHttpContextProvider, getHttpHandler } from "./contextProvider";
4
+ import {
5
+ getIntegrationConfig,
6
+ resolveIntegrationDetails,
7
+ IntegrationDetails,
8
+ QueueItIntegrationEndpointProvider,
9
+ } from "./integrationConfigProvider";
10
+ import { Utils } from "./sdk/QueueITHelpers";
11
+
12
+ const QUEUEIT_FAILED_HEADERNAME = "x-queueit-failed";
13
+ let httpProvider: FastlyHttpContextProvider | null = null;
14
+
15
+ export async function onQueueITRequest(
16
+ req: Request,
17
+ conf: IntegrationDetails | null = null
18
+ ): Promise<Response | null> {
19
+ if (conf == null) {
20
+ conf = resolveIntegrationDetails();
21
+ }
22
+ if (conf == null) {
23
+ return new Response("No integration details found.", {
24
+ headers: new Headers(),
25
+ status: 404,
26
+ });
27
+ }
28
+
29
+ const integrationProvider =
30
+ conf.provider == null
31
+ ? new QueueItIntegrationEndpointProvider()
32
+ : conf.provider;
33
+ QueueITHelper.configureKnownUserHashing();
34
+ httpProvider = getHttpHandler(req);
35
+
36
+ let integrationConfigJson = await getIntegrationConfig(conf, integrationProvider);
37
+ const requestUrl: string = conf.resolveWorkerRequestUrl(req.url);
38
+
39
+ const queueItToken = Utils.getParameterByName(
40
+ requestUrl,
41
+ KnownUser.QueueITTokenKey
42
+ );
43
+ const requestUrlWithoutToken: string = Utils.removeQueueItToken(requestUrl);
44
+
45
+ // The requestUrlWithoutToken is used to match Triggers and as the Target url (where to return the users to).
46
+ // It is therefor important that this is exactly the url of the users browsers. So, if your webserver is
47
+ // behind e.g. a load balancer that modifies the host name or port, reformat requestUrlWithoutToken before proceeding.
48
+ const validationResultPair = KnownUser.validateRequestByIntegrationConfig(
49
+ requestUrlWithoutToken,
50
+ queueItToken,
51
+ integrationConfigJson,
52
+ conf.customerId,
53
+ conf.secretKey,
54
+ httpProvider!
55
+ );
56
+
57
+ if (
58
+ validationResultPair.first != null &&
59
+ validationResultPair.first!.doRedirect()
60
+ ) {
61
+ const validationResult = validationResultPair.first!;
62
+
63
+ if (validationResult.isAjaxResult) {
64
+ let response = new Response(null, {
65
+ status: 200,
66
+ headers: httpProvider!.getHttpResponse().getHeaders(),
67
+ });
68
+ // In case of ajax call send the user to the queue by sending a custom queue-it header and redirecting user to queue from javascript
69
+ response.headers.set("Access-Control-Expose-Headers", validationResult.getAjaxQueueRedirectHeaderKey());
70
+ response.headers.set(
71
+ validationResult.getAjaxQueueRedirectHeaderKey(),
72
+ QueueITHelper.addKUPlatformVersion(
73
+ validationResult.getAjaxRedirectUrl()
74
+ )
75
+ );
76
+ Utils.addNoCacheHeaders(response);
77
+ return response;
78
+ } else {
79
+ let response = new Response(null, {
80
+ status: 302,
81
+ headers: httpProvider!.getHttpResponse().getHeaders(),
82
+ });
83
+ // Send the user to the queue - either because hash was missing or because is was invalid
84
+ response.headers.set(
85
+ "Location",
86
+ QueueITHelper.addKUPlatformVersion(validationResult.redirectUrl)
87
+ );
88
+ Utils.addNoCacheHeaders(response);
89
+ return response;
90
+ }
91
+ } else if (validationResultPair.first != null) {
92
+ const validationResult = validationResultPair.first!;
93
+ // Request can continue - we remove queueittoken form querystring parameter to avoid sharing of user specific token
94
+ // Support mobile scenario adding the condition !validationResult.isAjaxResult
95
+ if (
96
+ queueItToken != "" &&
97
+ !validationResult.isAjaxResult &&
98
+ validationResult.actionType == "Queue"
99
+ ) {
100
+ let response = new Response(null, {
101
+ status: 302,
102
+ headers: httpProvider!.getHttpResponse().getHeaders(),
103
+ });
104
+ response.headers.set("Location", requestUrlWithoutToken);
105
+ Utils.addNoCacheHeaders(response);
106
+ return response;
107
+ } else {
108
+ // lets caller decide the next step, or just serve the request normally
109
+ return null;
110
+ }
111
+ } else if (validationResultPair.second != null) {
112
+ httpProvider!.isError = true;
113
+ }
114
+
115
+ return null;
116
+ }
117
+
118
+ //Fill in the Queue-it headers
119
+ export function onQueueITResponse(res: Response): void {
120
+ const contextHeaders = httpProvider!.getHttpResponse().getHeaders();
121
+
122
+ if (httpProvider!.isError) {
123
+ res.headers.append(QUEUEIT_FAILED_HEADERNAME, "true");
124
+ }
125
+ for (const key of contextHeaders.keys()) {
126
+ if (key.length == 0) continue;
127
+ const value = contextHeaders.get(key);
128
+ if (value != null && value.length > 0)
129
+ res.headers.append(key, value);
130
+ }
131
+ }
@@ -1,24 +1,23 @@
1
- import { Headers } from "@fastly/as-compute";
2
-
3
- export interface IHttpRequest {
4
- getUserAgent(): string;
5
- getHeader(name: string): string;
6
- getAbsoluteUri(): string;
7
- getUserHostAddress(): string;
8
- getCookieValue(cookieKey: string): string;
9
- getRequestBodyAsString(): string;
10
- }
11
-
12
- export interface IHttpResponse {
13
- setCookie(cookieName: string, cookieValue: string, domain: string, expiration: i64): void;
14
- getHeaders(): Headers;
15
- }
16
-
17
- export interface IHttpContextProvider {
18
- getHttpRequest(): IHttpRequest;
19
- getHttpResponse(): IHttpResponse;
20
- }
21
-
22
- export interface IDateTimeProvider {
23
- getCurrentTime(): Date
24
- }
1
+
2
+ export interface IHttpRequest {
3
+ getUserAgent(): string;
4
+ getHeader(name: string): string;
5
+ getAbsoluteUri(): string;
6
+ getUserHostAddress(): string;
7
+ getCookieValue(cookieKey: string): string;
8
+ getRequestBodyAsString(): string;
9
+ }
10
+
11
+ export interface IHttpResponse {
12
+ setCookie(cookieName: string, cookieValue: string, domain: string, expiration: number): void;
13
+ getHeaders(): Headers;
14
+ }
15
+
16
+ export interface IHttpContextProvider {
17
+ getHttpRequest(): IHttpRequest;
18
+ getHttpResponse(): IHttpResponse;
19
+ }
20
+
21
+ export interface IDateTimeProvider {
22
+ getCurrentTime(): Date
23
+ }
@@ -0,0 +1,57 @@
1
+ import {
2
+ CustomerIntegration,
3
+ IntegrationConfigModel,
4
+ TriggerModel,
5
+ TriggerPart
6
+ } from "./IntegrationConfigModel";
7
+
8
+ export class CustomerIntegrationDecodingHandler {
9
+ static deserialize(integrationsConfigString: string): CustomerIntegration {
10
+ const result = new CustomerIntegration();
11
+ if (!integrationsConfigString) return result;
12
+
13
+ const parsed = JSON.parse(integrationsConfigString);
14
+ result.Version = parsed.Version ?? 0;
15
+ result.Description = parsed.Description ?? '';
16
+
17
+ if (Array.isArray(parsed.Integrations)) {
18
+ result.Integrations = parsed.Integrations.map((item: any) => {
19
+ const model = new IntegrationConfigModel();
20
+ model.Name = item.Name ?? '';
21
+ model.EventId = item.EventId ?? '';
22
+ model.CookieDomain = item.CookieDomain ?? '';
23
+ model.LayoutName = item.LayoutName ?? '';
24
+ model.Culture = item.Culture ?? '';
25
+ model.ExtendCookieValidity = item.ExtendCookieValidity ?? false;
26
+ model.CookieValidityMinute = item.CookieValidityMinute ?? 0;
27
+ model.QueueDomain = item.QueueDomain ?? '';
28
+ model.RedirectLogic = item.RedirectLogic ?? '';
29
+ model.ForcedTargetUrl = item.ForcedTargetUrl ?? '';
30
+ model.ActionType = item.ActionType ?? '';
31
+
32
+ model.Triggers = (item.Triggers ?? []).map((trigger: any) => {
33
+ const t = new TriggerModel();
34
+ t.LogicalOperator = trigger.LogicalOperator ?? '';
35
+ t.TriggerParts = (trigger.TriggerParts ?? []).map((part: any) => {
36
+ const tp = new TriggerPart();
37
+ tp.ValidatorType = part.ValidatorType ?? '';
38
+ tp.Operator = part.Operator ?? '';
39
+ tp.ValueToCompare = part.ValueToCompare ?? '';
40
+ tp.ValuesToCompare = part.ValuesToCompare ?? [];
41
+ tp.IsNegative = part.IsNegative ?? false;
42
+ tp.IsIgnoreCase = part.IsIgnoreCase ?? false;
43
+ tp.UrlPart = part.UrlPart ?? '';
44
+ tp.CookieName = part.CookieName ?? '';
45
+ tp.HttpHeaderName = part.HttpHeaderName ?? '';
46
+ return tp;
47
+ });
48
+ return t;
49
+ });
50
+
51
+ return model;
52
+ });
53
+ }
54
+
55
+ return result;
56
+ }
57
+ }