@contrail/flexplm 1.7.7-alpha.e0ee6a0 → 1.7.7-alpha.eb1d846

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,15 +1,3 @@
1
- export interface SessionReuseConfig {
2
- enabled?: boolean | string;
3
- ttlSeconds?: number | string;
4
- cookieName?: string;
5
- retryStatuses?: number | number[] | string;
6
- }
7
- export interface FlexPLMConnectConfig {
8
- staticHeaders?: {
9
- [key: string]: string;
10
- };
11
- sessionReuse?: SessionReuseConfig;
12
- }
13
1
  export interface FCConfig {
14
2
  apiKey?: string;
15
3
  orgSlug?: string;
@@ -17,7 +5,7 @@ export interface FCConfig {
17
5
  configFile?: string;
18
6
  eventObjectClassParam?: string;
19
7
  eventFlexTypePathParam?: string;
20
- flexplmConnect?: FlexPLMConnectConfig;
8
+ flexplmConnect?: any;
21
9
  taskId?: string;
22
10
  apiHost: string;
23
11
  userName(): string;
@@ -1,13 +1,28 @@
1
1
  import { FCConfig, FlexPLMResponseData, PayloadType } from '../interfaces/interfaces';
2
2
  export declare class FlexPLMConnect {
3
3
  private config;
4
- private sessions;
5
4
  private vibeEventEndpoint;
6
5
  private staticHeaders;
7
6
  payloadSendAsArray: boolean;
8
7
  constructor(_config: FCConfig, endPoint?: any, payloadAsArray?: any);
8
+ private get sessionOptions();
9
+ /**
10
+ * Waits until no cold session acquisition is running for this key.
11
+ * Callers must `await` this only when it returns a promise: awaiting even a resolved promise yields,
12
+ * and the check-then-register in runColdAcquisition has to stay synchronous to be race free.
13
+ */
14
+ private waitForInFlightAcquisition;
15
+ /** Runs a cold acquisition and registers it so concurrent callers wait for it instead of opening their own session. */
16
+ private runColdAcquisition;
17
+ private getSessionKey;
9
18
  /** Releases the connection of a rejected response before it is replaced by a retry. */
10
19
  private discardBody;
20
+ private getCachedSession;
21
+ private storeSession;
22
+ private clearSession;
23
+ /** Returns the session cookie value Windchill issued on this response, if any (last one wins). */
24
+ private extractSessionCookie;
25
+ private cookieHeader;
11
26
  private getRequestOptions;
12
27
  getCSRF(getNewSession?: boolean, rejectedCookie?: string): any;
13
28
  private fetchCSRF;
@@ -2,23 +2,62 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FlexPLMConnect = void 0;
4
4
  const app_framework_1 = require("@contrail/app-framework");
5
- const flexplm_session_manager_1 = require("./flexplm-session-manager");
6
- // Cookie values carry the session id: mask them in logs whatever the header-name casing.
7
- const maskCookieHeaders = (headers) => {
8
- if (!headers)
9
- return;
10
- for (const key of Object.keys(headers)) {
11
- if (key.toLowerCase() === 'cookie' && headers[key])
12
- headers[key] = '***masked***';
5
+ // Module-level on purpose: a new FlexPLMConnect is constructed for every event. Declaring for Session reusing use case.
6
+ const sessionCache = new Map();
7
+ // Upper bound so users/option combinations that are never requested again cannot accumulate cookies forever.
8
+ const MAX_CACHED_SESSIONS = 100;
9
+ const pruneSessionCache = () => {
10
+ const now = Date.now();
11
+ for (const [key, session] of sessionCache) {
12
+ if (session.expiresAt <= now)
13
+ sessionCache.delete(key);
13
14
  }
15
+ // Still full: drop the oldest entries (Map keeps insertion order).
16
+ while (sessionCache.size >= MAX_CACHED_SESSIONS) {
17
+ sessionCache.delete(sessionCache.keys().next().value);
18
+ }
19
+ };
20
+ // In-flight cold session acquisitions per key, so concurrent events share one FlexPLM session instead of each creating their own.
21
+ const inFlightAcquisitions = new Map();
22
+ const DEFAULT_SESSION_COOKIE_NAME = 'JSESSIONID';
23
+ const DEFAULT_SESSION_TTL_SECONDS = 900;
24
+ const DEFAULT_RETRY_STATUSES = [401, 403];
25
+ const COOKIE_NAME_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
26
+ // Thrown internally when a cached cookie was rejected, so the caller can re-acquire under the lock.
27
+ class SessionRejectedError extends Error {
28
+ }
29
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
30
+ const parseRetryStatuses = (value) => {
31
+ let list = [];
32
+ if (Array.isArray(value))
33
+ list = value;
34
+ else if (typeof value === 'string')
35
+ list = value.split(',');
36
+ else if (value !== undefined && value !== null)
37
+ list = [value];
38
+ const statuses = list
39
+ .map(status => (typeof status === 'string' ? status.trim() : status))
40
+ .filter(status => status !== '' && status !== null && status !== undefined)
41
+ .map(Number)
42
+ // Only client-error statuses can mean "session rejected". 2xx/5xx would resend events the server already processed.
43
+ .filter(status => Number.isInteger(status) && status >= 400 && status <= 499);
44
+ return statuses.length ? statuses : DEFAULT_RETRY_STATUSES;
45
+ };
46
+ const parseTtlSeconds = (value) => {
47
+ const ttl = Number(value);
48
+ return Number.isFinite(ttl) && ttl > 0 ? ttl : DEFAULT_SESSION_TTL_SECONDS;
14
49
  };
50
+ const parseCookieName = (value) => {
51
+ const name = typeof value === 'string' ? value.trim() : '';
52
+ return COOKIE_NAME_TOKEN.test(name) ? name : DEFAULT_SESSION_COOKIE_NAME;
53
+ };
54
+ // Added for Session reuse - ET-390 - Ends
15
55
  class FlexPLMConnect {
16
56
  constructor(_config, endPoint = undefined, payloadAsArray = undefined) {
17
57
  this.vibeEventEndpoint = '';
18
58
  this.staticHeaders = undefined;
19
59
  this.payloadSendAsArray = true;
20
60
  this.config = _config;
21
- this.sessions = new flexplm_session_manager_1.FlexPLMSessionManager(_config);
22
61
  this.vibeEventEndpoint = (endPoint)
23
62
  ? endPoint
24
63
  : this.config.vibeEventEndpoint;
@@ -29,7 +68,56 @@ class FlexPLMConnect {
29
68
  this.staticHeaders = this.config?.flexplmConnect?.staticHeaders;
30
69
  }
31
70
  }
32
- // ET-390 - Session reuse
71
+ /////////////////////////////////////////////////////////////////////////////
72
+ ///////// ET-390 - Session reuse: start
73
+ /////////////////////////////////////////////////////////////////////////////
74
+ get sessionOptions() {
75
+ const sessReuse = this.config?.flexplmConnect?.sessionReuse;
76
+ const enabled = sessReuse?.enabled;
77
+ return {
78
+ enabled: enabled === true || String(enabled).toLowerCase() === 'true',
79
+ ttlMs: parseTtlSeconds(sessReuse?.ttlSeconds) * 1000,
80
+ cookieName: parseCookieName(sessReuse?.cookieName),
81
+ retryStatuses: parseRetryStatuses(sessReuse?.retryStatuses),
82
+ };
83
+ }
84
+ /**
85
+ * Waits until no cold session acquisition is running for this key.
86
+ * Callers must `await` this only when it returns a promise: awaiting even a resolved promise yields,
87
+ * and the check-then-register in runColdAcquisition has to stay synchronous to be race free.
88
+ */
89
+ waitForInFlightAcquisition() {
90
+ const key = this.getSessionKey();
91
+ if (!inFlightAcquisitions.has(key))
92
+ return undefined;
93
+ return (async () => {
94
+ let pending = inFlightAcquisitions.get(key);
95
+ while (pending) {
96
+ await pending.catch(() => undefined);
97
+ pending = inFlightAcquisitions.get(key);
98
+ }
99
+ })();
100
+ }
101
+ /** Runs a cold acquisition and registers it so concurrent callers wait for it instead of opening their own session. */
102
+ async runColdAcquisition(acquire) {
103
+ const key = this.getSessionKey();
104
+ const acquisition = acquire();
105
+ inFlightAcquisitions.set(key, acquisition);
106
+ try {
107
+ return await acquisition;
108
+ }
109
+ finally {
110
+ if (inFlightAcquisitions.get(key) === acquisition)
111
+ inFlightAcquisitions.delete(key);
112
+ }
113
+ }
114
+ getSessionKey() {
115
+ // Options that change the cached value are part of the key; JSON avoids '|' collisions between fields.
116
+ const { cookieName, ttlMs } = this.sessionOptions;
117
+ return JSON.stringify([
118
+ this.config.apiHost, this.config.urlContext, this.config.userName(), this.config.plmEnviornment, cookieName, ttlMs,
119
+ ]);
120
+ }
33
121
  /** Releases the connection of a rejected response before it is replaced by a retry. */
34
122
  async discardBody(response) {
35
123
  try {
@@ -40,6 +128,60 @@ class FlexPLMConnect {
40
128
  // best effort: nothing to do if the body is already consumed or locked
41
129
  }
42
130
  }
131
+ getCachedSession() {
132
+ if (!this.sessionOptions.enabled)
133
+ return undefined;
134
+ const key = this.getSessionKey();
135
+ const cachedSessValue = sessionCache.get(key);
136
+ if (!cachedSessValue)
137
+ return undefined;
138
+ if (cachedSessValue.expiresAt <= Date.now()) {
139
+ sessionCache.delete(key);
140
+ return undefined;
141
+ }
142
+ return cachedSessValue.cookie;
143
+ }
144
+ storeSession(cookie) {
145
+ // sliding expiry: Windchill's session timeout is also sliding
146
+ const key = this.getSessionKey();
147
+ // delete first so a refreshed entry moves to the newest position (oldest-first eviction then acts as LRU)
148
+ sessionCache.delete(key);
149
+ pruneSessionCache();
150
+ sessionCache.set(key, { cookie, expiresAt: Date.now() + this.sessionOptions.ttlMs });
151
+ }
152
+ clearSession() {
153
+ sessionCache.delete(this.getSessionKey());
154
+ }
155
+ /** Returns the session cookie value Windchill issued on this response, if any (last one wins). */
156
+ extractSessionCookie(response) {
157
+ const respHeader = response?.headers;
158
+ if (!respHeader)
159
+ return undefined;
160
+ let raw = [];
161
+ if (typeof respHeader.getSetCookie === 'function') {
162
+ raw = respHeader.getSetCookie();
163
+ }
164
+ else if (typeof respHeader.get === 'function' && respHeader.get('set-cookie')) {
165
+ raw = [respHeader.get('set-cookie')];
166
+ }
167
+ const name = this.sessionOptions.cookieName;
168
+ const regexFilter = new RegExp('(?:^|[,\\s])' + escapeRegExp(name) + '=([^;,\\s]+)', 'g');
169
+ let jSession;
170
+ for (const line of raw) {
171
+ let cookieNameMatcher = regexFilter.exec(line);
172
+ while (cookieNameMatcher !== null) {
173
+ jSession = cookieNameMatcher[1];
174
+ cookieNameMatcher = regexFilter.exec(line);
175
+ }
176
+ }
177
+ return jSession;
178
+ }
179
+ cookieHeader(sessionCookie) {
180
+ return sessionCookie ? `${this.sessionOptions.cookieName}=${sessionCookie}` : undefined;
181
+ }
182
+ /////////////////////////////////////////////////////////////////////////////
183
+ ///////// ET-390 - Session reuse: end
184
+ /////////////////////////////////////////////////////////////////////////////
43
185
  /////////////////////////////////////////////////////////////////////////////
44
186
  ///////// Custom getRequestOptions: start
45
187
  /////////////////////////////////////////////////////////////////////////////
@@ -57,21 +199,17 @@ class FlexPLMConnect {
57
199
  Object.assign(csrfOptions.headers, this.staticHeaders);
58
200
  }
59
201
  // Added for Session reuse - ET-390 - Starts
60
- // Merge with a configured static Cookie header (any header-name casing) instead of replacing it.
61
- const headers = csrfOptions.headers;
62
- const staticCookieKeys = Object.keys(headers).filter(key => key.toLowerCase() === 'cookie');
63
- const staticCookie = staticCookieKeys.map(key => headers[key]).join('; ');
64
- const cookie = this.sessions.buildCookieHeader(staticCookie, sessionCookie);
65
- staticCookieKeys.forEach(key => delete headers[key]);
202
+ const cookie = this.cookieHeader(sessionCookie);
66
203
  if (cookie) {
67
- headers['Cookie'] = cookie;
204
+ csrfOptions.headers['Cookie'] = cookie;
68
205
  }
69
206
  // Added for Session reuse - ET-390 - Ends
70
207
  if (app_framework_1.Logger.isInfoOn()) {
71
208
  const logOptions = JSON.parse(JSON.stringify(csrfOptions));
72
209
  logOptions['headers']['Authorization'] = logOptions?.headers?.Authorization.substring(0, 9);
73
210
  // Added for Session reuse - ET-390 - Starts
74
- maskCookieHeaders(logOptions.headers);
211
+ if (logOptions.headers['Cookie'])
212
+ logOptions.headers['Cookie'] = '***masked***';
75
213
  // Added for Session reuse - ET-390 - Ends
76
214
  console.info('csrfOptions: ' + JSON.stringify(logOptions));
77
215
  }
@@ -85,30 +223,30 @@ class FlexPLMConnect {
85
223
  // rejectedCookie: the cookie that was rejected by the caller, so a refresh already done by a concurrent event is not thrown away
86
224
  async getCSRF(getNewSession = false, rejectedCookie) {
87
225
  // Added for Session reuse - ET-390 - Starts
88
- if (!this.sessions.options.enabled)
226
+ if (!this.sessionOptions.enabled)
89
227
  return this.fetchCSRF(undefined);
90
- for (let wait = this.sessions.waitForInFlightAcquisition(); wait; wait = this.sessions.waitForInFlightAcquisition())
228
+ for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
91
229
  await wait;
92
230
  if (getNewSession) {
93
- const current = this.sessions.getCachedSession();
231
+ const current = this.getCachedSession();
94
232
  if (rejectedCookie === undefined || !current || current === rejectedCookie)
95
- this.sessions.clearSession();
233
+ this.clearSession();
96
234
  }
97
- const cached = this.sessions.getCachedSession();
235
+ const cached = this.getCachedSession();
98
236
  if (cached) {
99
237
  try {
100
238
  return await this.fetchCSRF(cached);
101
239
  }
102
240
  catch (e) {
103
- if (!(e instanceof flexplm_session_manager_1.SessionRejectedError))
241
+ if (!(e instanceof SessionRejectedError))
104
242
  throw e;
105
243
  // if the cached cookie is rejected (401/403), drop it and acquire a new session (serialized)
106
- if (this.sessions.getCachedSession() === cached)
107
- this.sessions.clearSession();
244
+ if (this.getCachedSession() === cached)
245
+ this.clearSession();
108
246
  return this.getCSRF();
109
247
  }
110
248
  }
111
- return this.sessions.runColdAcquisition(() => this.fetchCSRF(undefined));
249
+ return this.runColdAcquisition(() => this.fetchCSRF(undefined));
112
250
  // Added for Session reuse - ET-390 - Ends
113
251
  }
114
252
  async fetchCSRF(sentCookie) {
@@ -120,10 +258,10 @@ class FlexPLMConnect {
120
258
  const csrfOptions = this.getRequestOptions('GET', sentCookie);
121
259
  const response = await fetch(csrfURL, csrfOptions);
122
260
  // Added for Session reuse - ET-390 - Starts
123
- if (sentCookie && this.sessions.options.retryStatuses.includes(response.status)) {
261
+ if (sentCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
124
262
  console.warn('Cached FlexPLM session rejected on csrf call (status ' + response.status + '). Retrying with a new session.');
125
263
  await this.discardBody(response);
126
- throw new flexplm_session_manager_1.SessionRejectedError();
264
+ throw new SessionRejectedError();
127
265
  }
128
266
  // Added for Session reuse - ET-390 - Ends
129
267
  if (response.status >= 300) {
@@ -137,10 +275,10 @@ class FlexPLMConnect {
137
275
  // Added for Session reuse - ET-390 - Starts
138
276
  // If the cookie we sent was invalid, Windchill answers with a fresh Set-Cookie --> replace the cache.
139
277
  let sessionCookie = sentCookie;
140
- if (this.sessions.options.enabled) {
141
- sessionCookie = this.sessions.extractSessionCookie(response) ?? sentCookie;
278
+ if (this.sessionOptions.enabled) {
279
+ sessionCookie = this.extractSessionCookie(response) ?? sentCookie;
142
280
  if (sessionCookie)
143
- this.sessions.storeSession(sessionCookie, sentCookie);
281
+ this.storeSession(sessionCookie);
144
282
  }
145
283
  // Added for Session reuse - ET-390 - Ends
146
284
  try {
@@ -176,7 +314,8 @@ class FlexPLMConnect {
176
314
  const logOptions = JSON.parse(JSON.stringify(xferOptions));
177
315
  if (logOptions?.headers?.Authorization)
178
316
  logOptions.headers.Authorization = logOptions?.headers?.Authorization.substring(0, 9);
179
- maskCookieHeaders(logOptions?.headers);
317
+ if (logOptions?.headers?.Cookie)
318
+ logOptions.headers.Cookie = '***masked***';
180
319
  if (csrf?.nonce_key)
181
320
  logOptions.headers[csrf.nonce_key] = csrf.nonce ? `***masked(length:${csrf.nonce.length})***` : '***masked(empty)***';
182
321
  console.info('csrfOptions: ' + JSON.stringify(logOptions));
@@ -203,7 +342,7 @@ class FlexPLMConnect {
203
342
  /// Added for Session reuse - ET-390 - Starts
204
343
  // const response = await this.sendRequest(csrf, payload);
205
344
  let response = await this.sendRequest(csrf, payload);
206
- if (csrf.sessionCookie && this.sessions.options.retryStatuses.includes(response.status)) {
345
+ if (csrf.sessionCookie && this.sessionOptions.retryStatuses.includes(response.status)) {
207
346
  console.warn('FlexPLM rejected session/nonce (status ' + response.status + '). Getting a new session and retrying once.');
208
347
  await this.discardBody(response);
209
348
  csrf = await this.getCSRF(true, csrf.sessionCookie);
@@ -264,30 +403,30 @@ class FlexPLMConnect {
264
403
  const vibeEventsURL = this.config.apiHost + urlContext + path;
265
404
  // Added for Session reuse - ET-390 - Starts
266
405
  const attempt = async () => {
267
- if (!this.sessions.options.enabled) {
406
+ if (!this.sessionOptions.enabled) {
268
407
  return { response: await fetch(vibeEventsURL, this.getRequestOptions('GET')), sent: undefined };
269
408
  }
270
- for (let wait = this.sessions.waitForInFlightAcquisition(); wait; wait = this.sessions.waitForInFlightAcquisition())
409
+ for (let wait = this.waitForInFlightAcquisition(); wait; wait = this.waitForInFlightAcquisition())
271
410
  await wait;
272
- const sent = this.sessions.getCachedSession();
411
+ const sent = this.getCachedSession();
273
412
  const call = async () => {
274
413
  const res = await fetch(vibeEventsURL, this.getRequestOptions('GET', sent));
275
414
  // A rejected cookie must not be stored again; only keep a cookie that was accepted or newly issued.
276
- if (!(sent && this.sessions.options.retryStatuses.includes(res.status))) {
277
- const cookie = this.sessions.extractSessionCookie(res) ?? sent;
415
+ if (!(sent && this.sessionOptions.retryStatuses.includes(res.status))) {
416
+ const cookie = this.extractSessionCookie(res) ?? sent;
278
417
  if (cookie)
279
- this.sessions.storeSession(cookie, sent);
418
+ this.storeSession(cookie);
280
419
  }
281
420
  return { response: res, sent };
282
421
  };
283
- return sent ? call() : this.sessions.runColdAcquisition(call);
422
+ return sent ? call() : this.runColdAcquisition(call);
284
423
  };
285
424
  const first = await attempt();
286
425
  let response = first.response;
287
- if (first.sent && this.sessions.options.retryStatuses.includes(response.status)) {
426
+ if (first.sent && this.sessionOptions.retryStatuses.includes(response.status)) {
288
427
  await this.discardBody(response);
289
- if (this.sessions.getCachedSession() === first.sent)
290
- this.sessions.clearSession();
428
+ if (this.getCachedSession() === first.sent)
429
+ this.clearSession();
291
430
  response = (await attempt()).response;
292
431
  }
293
432
  // Added for Session reuse - ET-390 - Ends
@@ -39,7 +39,7 @@ const resp = (status, setCookie = [], json = csrfBody) => ({
39
39
  });
40
40
  let userCounter = 0;
41
41
  const uniqueUser = () => 'sess-user-' + (++userCounter);
42
- // Session options are nested: { flexplmConnect: { sessionReuse: { enabled, ... } } }
42
+ // The connector config nests the entries: { flexplmConnect: { sessionReuse: { enabled: true, ... } } }
43
43
  const sessionConfig = (user, sessionReuse = { enabled: true }) => createConfig({ userName: () => user, flexplmConnect: { sessionReuse } });
44
44
  const fetchMock = () => global.fetch;
45
45
  const callHeaders = (i) => fetchMock().mock.calls[i][1].headers;
@@ -354,60 +354,6 @@ describe('FlexPLMConnect session reuse', () => {
354
354
  isInfoOn.mockRestore();
355
355
  info.mockRestore();
356
356
  });
357
- describe('static Cookie header', () => {
358
- const withStatic = (user, staticHeaders, sessionReuse = { enabled: true }) => createConfig({ userName: () => user, flexplmConnect: { sessionReuse, staticHeaders } });
359
- it('should keep other static cookies and replace only the managed one once a session is cached', async () => {
360
- const u = uniqueUser();
361
- fetchMock()
362
- .mockResolvedValueOnce(resp(200, ['JSESSIONID=new.tomcat1; Path=/']))
363
- .mockResolvedValueOnce(resp(200, [], {}));
364
- await new flexplm_connect_1.FlexPLMConnect(withStatic(u, { Cookie: 'lb=abc; JSESSIONID=stale; theme=dark' })).sendToFlexPLM(payload);
365
- expect(callHeaders(0).Cookie).toBe('lb=abc; theme=dark'); // cold: stale managed cookie dropped
366
- expect(callHeaders(1).Cookie).toBe('lb=abc; theme=dark; JSESSIONID=new.tomcat1');
367
- });
368
- it('should send a single Cookie header when the static header name is lowercase', async () => {
369
- const u = uniqueUser();
370
- fetchMock()
371
- .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1; Path=/']))
372
- .mockResolvedValueOnce(resp(200, [], {}));
373
- await new flexplm_connect_1.FlexPLMConnect(withStatic(u, { cookie: 'lb=abc' })).sendToFlexPLM(payload);
374
- const postHeaders = callHeaders(1);
375
- expect(Object.keys(postHeaders).filter(k => k.toLowerCase() === 'cookie')).toEqual(['Cookie']);
376
- expect(postHeaders.Cookie).toBe('lb=abc; JSESSIONID=abc.tomcat1');
377
- });
378
- it('should send the static Cookie unchanged when session reuse is disabled', async () => {
379
- const u = uniqueUser();
380
- fetchMock()
381
- .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1; Path=/']))
382
- .mockResolvedValueOnce(resp(200, [], {}));
383
- await new flexplm_connect_1.FlexPLMConnect(withStatic(u, { Cookie: 'lb=abc; JSESSIONID=static' }, { enabled: false })).sendToFlexPLM(payload);
384
- expect(callHeaders(0).Cookie).toBe('lb=abc; JSESSIONID=static');
385
- expect(callHeaders(1).Cookie).toBe('lb=abc; JSESSIONID=static');
386
- });
387
- it('should not resend a rejected static JSESSIONID on the fresh retry', async () => {
388
- const u = uniqueUser();
389
- fetchMock()
390
- .mockResolvedValueOnce(resp(200, ['JSESSIONID=old.tomcat1; Path=/']))
391
- .mockResolvedValueOnce(resp(403, [], {})) // POST rejected
392
- .mockResolvedValueOnce(resp(200, ['JSESSIONID=fresh.tomcat1; Path=/'])) // fresh GET
393
- .mockResolvedValueOnce(resp(200, [], {}));
394
- await new flexplm_connect_1.FlexPLMConnect(withStatic(u, { Cookie: 'lb=abc; JSESSIONID=static' })).sendToFlexPLM(payload);
395
- expect(callHeaders(2).Cookie).toBe('lb=abc'); // fresh GET carries no JSESSIONID
396
- expect(callHeaders(3).Cookie).toBe('lb=abc; JSESSIONID=fresh.tomcat1');
397
- });
398
- it('should mask a lowercase static cookie header in logs', async () => {
399
- const isInfoOn = jest.spyOn(app_framework_1.Logger, 'isInfoOn').mockReturnValue(true);
400
- const info = jest.spyOn(console, 'info').mockImplementation();
401
- fetchMock()
402
- .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1']))
403
- .mockResolvedValueOnce(resp(200, [], {}));
404
- await new flexplm_connect_1.FlexPLMConnect(withStatic(uniqueUser(), { cookie: 'lb=topsecret' }, { enabled: false })).sendToFlexPLM(payload);
405
- const logged = info.mock.calls.map(c => String(c[0] ?? '')).join('\n');
406
- expect(logged).not.toContain('topsecret');
407
- isInfoOn.mockRestore();
408
- info.mockRestore();
409
- });
410
- });
411
357
  describe('option normalisation', () => {
412
358
  const rejectedOnceThenOk = (u, opts) => {
413
359
  fetchMock()
@@ -575,41 +521,6 @@ describe('FlexPLMConnect session reuse', () => {
575
521
  describe('concurrent session acquisition', () => {
576
522
  const flush = () => new Promise(r => setImmediate(r));
577
523
  const isColdGet = (call) => call[1].method === 'GET' && !call[1].headers.Cookie;
578
- it('should not let a late response using an older cookie roll back a refreshed session', async () => {
579
- const u = uniqueUser();
580
- const cfg = () => sessionConfig(u);
581
- // seed the cache with 'old'
582
- fetchMock()
583
- .mockResolvedValueOnce(resp(200, ['JSESSIONID=old']))
584
- .mockResolvedValueOnce(resp(200, [], {}));
585
- await new flexplm_connect_1.FlexPLMConnect(cfg()).sendToFlexPLM(payload);
586
- let lateGetsSeen = 0;
587
- let releaseLate;
588
- const lateGate = new Promise(r => { releaseLate = r; });
589
- fetchMock().mockReset();
590
- fetchMock().mockImplementation(async (_url, opts) => {
591
- const cookie = opts.headers.Cookie;
592
- if (opts.method === 'GET' && cookie === 'JSESSIONID=old') {
593
- if (++lateGetsSeen === 1)
594
- return resp(403, []); // event A: old rejected
595
- await lateGate; // event B: slow 200, no Set-Cookie
596
- return resp(200, []);
597
- }
598
- if (opts.method === 'GET' && !cookie)
599
- return resp(200, ['JSESSIONID=new']); // A's fresh acquisition
600
- if (opts.method === 'GET')
601
- return resp(200, []);
602
- return resp(200, [], {});
603
- });
604
- const a = new flexplm_connect_1.FlexPLMConnect(cfg()).sendToFlexPLM(payload);
605
- const b = new flexplm_connect_1.FlexPLMConnect(cfg()).sendToFlexPLM(payload);
606
- await a;
607
- releaseLate();
608
- await b;
609
- fetchMock().mockClear();
610
- await new flexplm_connect_1.FlexPLMConnect(cfg()).getCSRF();
611
- expect(callHeaders(0).Cookie).toBe('JSESSIONID=new'); // B must not have stored 'old' again
612
- });
613
524
  it('should share one session across concurrent events on a cold cache', async () => {
614
525
  const u = uniqueUser();
615
526
  let release;
@@ -695,6 +606,15 @@ describe('FlexPLMConnect session reuse - feature disabled (default)', () => {
695
606
  await new flexplm_connect_1.FlexPLMConnect(sessionConfig(u, { enabled: false })).sendToFlexPLM(payload);
696
607
  expect(callHeaders(1).Cookie).toBeUndefined();
697
608
  });
609
+ it('should ignore the legacy flat key form', async () => {
610
+ const u = uniqueUser();
611
+ fetchMock()
612
+ .mockResolvedValueOnce(resp(200, ['JSESSIONID=abc.tomcat1'])) // Set-Cookie present but must be ignored
613
+ .mockResolvedValueOnce(resp(200, [], {}));
614
+ const cfg = createConfig({ userName: () => u, 'flexplmConnect.sessionReuse.enabled': true });
615
+ await new flexplm_connect_1.FlexPLMConnect(cfg).sendToFlexPLM(payload);
616
+ expect(callHeaders(1).Cookie).toBeUndefined();
617
+ });
698
618
  });
699
619
  describe('FlexPLMConnect.getRequest session reuse', () => {
700
620
  it('should send the cached cookie on image/GET requests', async () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contrail/flexplm",
3
- "version": "1.7.7-alpha.e0ee6a0",
3
+ "version": "1.7.7-alpha.eb1d846",
4
4
  "description": "Library used for integration with flexplm.",
5
5
  "main": "lib/index.js",
6
6
  "types": "lib/index.d.ts",
@@ -1,40 +0,0 @@
1
- import { FCConfig } from '../interfaces/interfaces';
2
- export declare class SessionRejectedError extends Error {
3
- }
4
- /** Owns the FlexPLM session cookie cache: options, keying, expiry, in-flight acquisition sharing and Set-Cookie parsing. */
5
- export declare class FlexPLMSessionManager {
6
- private config;
7
- constructor(config: FCConfig);
8
- get options(): {
9
- enabled: boolean;
10
- ttlMs: number;
11
- cookieName: string;
12
- retryStatuses: number[];
13
- };
14
- /**
15
- * Waits until no cold session acquisition is running for this key.
16
- * Callers must `await` this only when it returns a promise: awaiting even a resolved promise yields,
17
- * and the check-then-register in runColdAcquisition has to stay synchronous to be race free.
18
- */
19
- waitForInFlightAcquisition(): Promise<void> | undefined;
20
- /** Runs a cold acquisition and registers it so concurrent callers wait for it instead of opening their own session. */
21
- runColdAcquisition<T>(acquire: () => Promise<T>): Promise<T>;
22
- private getSessionKey;
23
- getCachedSession(): string | undefined;
24
- /**
25
- * Compare-and-set: stores `cookie` only if the cache still holds the cookie this request was sent with
26
- * (`sentCookie`, undefined for a cold acquisition = nothing cached). A late response must not roll back or
27
- * resurrect a session that a concurrent event already replaced or cleared.
28
- * @returns true if the cache was updated
29
- */
30
- storeSession(cookie: string, sentCookie: string | undefined): boolean;
31
- clearSession(): void;
32
- /** Returns the session cookie value Windchill issued on this response, if any (last one wins). */
33
- extractSessionCookie(response: Response): string | undefined;
34
- /**
35
- * Builds the Cookie header value from the configured static Cookie header and the managed session cookie.
36
- * With session reuse enabled only the managed cookie is replaced/removed; every other static cookie pair is kept.
37
- * With session reuse disabled the static value is returned unchanged.
38
- */
39
- buildCookieHeader(staticCookie?: string, sessionCookie?: string): string | undefined;
40
- }
@@ -1,180 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FlexPLMSessionManager = exports.SessionRejectedError = void 0;
4
- // Module-level on purpose: a new FlexPLMConnect (and session manager) is constructed for every event.
5
- const sessionCache = new Map();
6
- // Upper bound so users/option combinations that are never requested again cannot accumulate cookies forever.
7
- const MAX_CACHED_SESSIONS = 100;
8
- const pruneSessionCache = () => {
9
- const now = Date.now();
10
- for (const [key, session] of sessionCache) {
11
- if (session.expiresAt <= now)
12
- sessionCache.delete(key);
13
- }
14
- // Still full: drop the oldest entries (Map keeps insertion order).
15
- while (sessionCache.size >= MAX_CACHED_SESSIONS) {
16
- sessionCache.delete(sessionCache.keys().next().value);
17
- }
18
- };
19
- // In-flight cold session acquisitions per key, so concurrent events share one FlexPLM session instead of each creating their own.
20
- const inFlightAcquisitions = new Map();
21
- const DEFAULT_SESSION_COOKIE_NAME = 'JSESSIONID';
22
- const DEFAULT_SESSION_TTL_SECONDS = 900;
23
- const DEFAULT_RETRY_STATUSES = [401, 403];
24
- const COOKIE_NAME_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
25
- // Thrown internally when a cached cookie was rejected, so the caller can re-acquire under the lock.
26
- class SessionRejectedError extends Error {
27
- }
28
- exports.SessionRejectedError = SessionRejectedError;
29
- const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
30
- const parseRetryStatuses = (value) => {
31
- let list = [];
32
- if (Array.isArray(value))
33
- list = value;
34
- else if (typeof value === 'string')
35
- list = value.split(',');
36
- else if (value !== undefined && value !== null)
37
- list = [value];
38
- const statuses = list
39
- .map(status => (typeof status === 'string' ? status.trim() : status))
40
- .filter(status => status !== '' && status !== null && status !== undefined)
41
- .map(Number)
42
- // Only client-error statuses can mean "session rejected". 2xx/5xx would resend events the server already processed.
43
- .filter(status => Number.isInteger(status) && status >= 400 && status <= 499);
44
- return statuses.length ? statuses : DEFAULT_RETRY_STATUSES;
45
- };
46
- const parseTtlSeconds = (value) => {
47
- const ttl = Number(value);
48
- return Number.isFinite(ttl) && ttl > 0 ? ttl : DEFAULT_SESSION_TTL_SECONDS;
49
- };
50
- const parseCookieName = (value) => {
51
- const name = typeof value === 'string' ? value.trim() : '';
52
- return COOKIE_NAME_TOKEN.test(name) ? name : DEFAULT_SESSION_COOKIE_NAME;
53
- };
54
- /** Owns the FlexPLM session cookie cache: options, keying, expiry, in-flight acquisition sharing and Set-Cookie parsing. */
55
- class FlexPLMSessionManager {
56
- constructor(config) {
57
- this.config = config;
58
- }
59
- get options() {
60
- const sessionReuseConfig = this.config?.flexplmConnect?.sessionReuse ?? {};
61
- return {
62
- enabled: sessionReuseConfig.enabled === true || String(sessionReuseConfig.enabled).toLowerCase() === 'true',
63
- ttlMs: parseTtlSeconds(sessionReuseConfig.ttlSeconds) * 1000,
64
- cookieName: parseCookieName(sessionReuseConfig.cookieName),
65
- retryStatuses: parseRetryStatuses(sessionReuseConfig.retryStatuses),
66
- };
67
- }
68
- /**
69
- * Waits until no cold session acquisition is running for this key.
70
- * Callers must `await` this only when it returns a promise: awaiting even a resolved promise yields,
71
- * and the check-then-register in runColdAcquisition has to stay synchronous to be race free.
72
- */
73
- waitForInFlightAcquisition() {
74
- const key = this.getSessionKey();
75
- if (!inFlightAcquisitions.has(key))
76
- return undefined;
77
- return (async () => {
78
- let pending = inFlightAcquisitions.get(key);
79
- while (pending) {
80
- await pending.catch(() => undefined);
81
- pending = inFlightAcquisitions.get(key);
82
- }
83
- })();
84
- }
85
- /** Runs a cold acquisition and registers it so concurrent callers wait for it instead of opening their own session. */
86
- async runColdAcquisition(acquire) {
87
- const key = this.getSessionKey();
88
- const acquisition = acquire();
89
- inFlightAcquisitions.set(key, acquisition);
90
- try {
91
- return await acquisition;
92
- }
93
- finally {
94
- if (inFlightAcquisitions.get(key) === acquisition)
95
- inFlightAcquisitions.delete(key);
96
- }
97
- }
98
- getSessionKey() {
99
- // Options that change the cached value are part of the key; JSON avoids '|' collisions between fields.
100
- const { cookieName, ttlMs } = this.options;
101
- return JSON.stringify([
102
- this.config.apiHost, this.config.urlContext, this.config.userName(), this.config.plmEnviornment, cookieName, ttlMs,
103
- ]);
104
- }
105
- getCachedSession() {
106
- if (!this.options.enabled)
107
- return undefined;
108
- const key = this.getSessionKey();
109
- const cachedSessValue = sessionCache.get(key);
110
- if (!cachedSessValue)
111
- return undefined;
112
- if (cachedSessValue.expiresAt <= Date.now()) {
113
- sessionCache.delete(key);
114
- return undefined;
115
- }
116
- return cachedSessValue.cookie;
117
- }
118
- /**
119
- * Compare-and-set: stores `cookie` only if the cache still holds the cookie this request was sent with
120
- * (`sentCookie`, undefined for a cold acquisition = nothing cached). A late response must not roll back or
121
- * resurrect a session that a concurrent event already replaced or cleared.
122
- * @returns true if the cache was updated
123
- */
124
- storeSession(cookie, sentCookie) {
125
- const key = this.getSessionKey();
126
- if (sessionCache.get(key)?.cookie !== sentCookie)
127
- return false;
128
- // sliding expiry: Windchill's session timeout is also sliding
129
- // delete first so a refreshed entry moves to the newest position (oldest-first eviction then acts as LRU)
130
- sessionCache.delete(key);
131
- pruneSessionCache();
132
- sessionCache.set(key, { cookie, expiresAt: Date.now() + this.options.ttlMs });
133
- return true;
134
- }
135
- clearSession() {
136
- sessionCache.delete(this.getSessionKey());
137
- }
138
- /** Returns the session cookie value Windchill issued on this response, if any (last one wins). */
139
- extractSessionCookie(response) {
140
- const respHeader = response?.headers;
141
- if (!respHeader)
142
- return undefined;
143
- let raw = [];
144
- if (typeof respHeader.getSetCookie === 'function') {
145
- raw = respHeader.getSetCookie();
146
- }
147
- else if (typeof respHeader.get === 'function' && respHeader.get('set-cookie')) {
148
- raw = [respHeader.get('set-cookie')];
149
- }
150
- const name = this.options.cookieName;
151
- const regexFilter = new RegExp('(?:^|[,\\s])' + escapeRegExp(name) + '=([^;,\\s]+)', 'g');
152
- let jSession;
153
- for (const line of raw) {
154
- let cookieNameMatcher = regexFilter.exec(line);
155
- while (cookieNameMatcher !== null) {
156
- jSession = cookieNameMatcher[1];
157
- cookieNameMatcher = regexFilter.exec(line);
158
- }
159
- }
160
- return jSession;
161
- }
162
- /**
163
- * Builds the Cookie header value from the configured static Cookie header and the managed session cookie.
164
- * With session reuse enabled only the managed cookie is replaced/removed; every other static cookie pair is kept.
165
- * With session reuse disabled the static value is returned unchanged.
166
- */
167
- buildCookieHeader(staticCookie, sessionCookie) {
168
- if (!this.options.enabled)
169
- return staticCookie || undefined;
170
- const name = this.options.cookieName;
171
- const pairs = (staticCookie ?? '')
172
- .split(';')
173
- .map(pair => pair.trim())
174
- .filter(pair => pair && pair.split('=')[0].trim() !== name);
175
- if (sessionCookie)
176
- pairs.push(`${name}=${sessionCookie}`);
177
- return pairs.length ? pairs.join('; ') : undefined;
178
- }
179
- }
180
- exports.FlexPLMSessionManager = FlexPLMSessionManager;
@@ -1 +0,0 @@
1
- export {};
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const flexplm_session_manager_1 = require("./flexplm-session-manager");
4
- let userCounter = 0;
5
- const newManager = () => {
6
- const user = 'mgr-user-' + (++userCounter);
7
- const config = {
8
- apiHost: 'https://flexplm.example.com',
9
- urlContext: '/FlexPLM',
10
- vibeEventEndpoint: '/api/events',
11
- csrfEndpoint: '/csrf',
12
- plmEnviornment: 'test',
13
- userName: () => user,
14
- password: () => 'pass',
15
- itemPreDevelopmentLifecycleStages: [],
16
- flexplmConnect: { sessionReuse: { enabled: true } },
17
- };
18
- return new flexplm_session_manager_1.FlexPLMSessionManager(config);
19
- };
20
- describe('FlexPLMSessionManager.storeSession (compare-and-set)', () => {
21
- it('should store a cold acquisition when nothing is cached', () => {
22
- const m = newManager();
23
- expect(m.storeSession('a', undefined)).toBe(true);
24
- expect(m.getCachedSession()).toBe('a');
25
- });
26
- it('should not let a cold acquisition overwrite an entry that appeared meanwhile', () => {
27
- const m = newManager();
28
- m.storeSession('a', undefined);
29
- expect(m.storeSession('b', undefined)).toBe(false);
30
- expect(m.getCachedSession()).toBe('a');
31
- });
32
- it('should replace or refresh the entry while it still holds the cookie that was sent', () => {
33
- const m = newManager();
34
- m.storeSession('old', undefined);
35
- expect(m.storeSession('new', 'old')).toBe(true);
36
- expect(m.getCachedSession()).toBe('new');
37
- expect(m.storeSession('new', 'new')).toBe(true); // sliding refresh with the same cookie
38
- });
39
- it('should ignore a late response that was sent with an older cookie', () => {
40
- const m = newManager();
41
- m.storeSession('old', undefined);
42
- m.storeSession('new', 'old');
43
- expect(m.storeSession('old', 'old')).toBe(false);
44
- expect(m.getCachedSession()).toBe('new');
45
- });
46
- it('should not resurrect a session that was cleared meanwhile', () => {
47
- const m = newManager();
48
- m.storeSession('old', undefined);
49
- m.clearSession();
50
- expect(m.storeSession('old', 'old')).toBe(false);
51
- expect(m.getCachedSession()).toBeUndefined();
52
- });
53
- });