emailengine-app 2.76.0 → 2.78.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/.github/workflows/release.yaml +24 -19
  2. package/.github/workflows/test.yml +80 -0
  3. package/.ncurc.js +14 -2
  4. package/.release-please-manifest.json +3 -0
  5. package/CHANGELOG.md +54 -0
  6. package/README.md +1 -1
  7. package/bin/emailengine.js +1 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +72 -5
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +75 -26
  12. package/lib/address-strategies.js +18 -0
  13. package/lib/api-reference/code-samples.js +194 -0
  14. package/lib/api-reference/format.js +193 -0
  15. package/lib/api-reference/index.js +222 -0
  16. package/lib/api-reference/model.js +338 -0
  17. package/lib/api-reference/schema-tree.js +366 -0
  18. package/lib/api-routes/account-routes.js +136 -39
  19. package/lib/api-routes/behavior-notes.js +57 -0
  20. package/lib/api-routes/blocklist-routes.js +9 -9
  21. package/lib/api-routes/changes-routes.js +6 -4
  22. package/lib/api-routes/chat-routes.js +3 -3
  23. package/lib/api-routes/delivery-test-routes.js +24 -6
  24. package/lib/api-routes/export-routes.js +14 -12
  25. package/lib/api-routes/gateway-routes.js +11 -11
  26. package/lib/api-routes/license-routes.js +7 -7
  27. package/lib/api-routes/mailbox-routes.js +18 -9
  28. package/lib/api-routes/message-routes.js +55 -35
  29. package/lib/api-routes/oauth2-app-routes.js +22 -16
  30. package/lib/api-routes/outbox-routes.js +7 -7
  31. package/lib/api-routes/pubsub-routes.js +3 -3
  32. package/lib/api-routes/settings-routes.js +10 -9
  33. package/lib/api-routes/stats-routes.js +3 -3
  34. package/lib/api-routes/submit-routes.js +58 -8
  35. package/lib/api-routes/template-routes.js +13 -13
  36. package/lib/api-routes/token-routes.js +15 -10
  37. package/lib/api-routes/webhook-route-routes.js +5 -5
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/autodetect-imap-settings.js +40 -16
  41. package/lib/base32.js +30 -0
  42. package/lib/bounce-detect.js +182 -62
  43. package/lib/consts.js +7 -0
  44. package/lib/egress-filter.js +89 -8
  45. package/lib/email-client/base-client.js +72 -82
  46. package/lib/email-client/gmail-client.js +3 -3
  47. package/lib/email-client/imap/listing-diff.js +3 -3
  48. package/lib/email-client/imap/mailbox.js +5 -69
  49. package/lib/email-client/imap-client.js +3 -2
  50. package/lib/email-client/message-builder.js +13 -13
  51. package/lib/email-client/outlook-client.js +1 -1
  52. package/lib/enum-descriptions.js +130 -0
  53. package/lib/export.js +1 -1
  54. package/lib/gateway.js +1 -1
  55. package/lib/get-raw-email.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-connection.js +2 -2
  57. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  58. package/lib/imapproxy/imap-server.js +42 -28
  59. package/lib/imapproxy/upstream-client.js +38 -0
  60. package/lib/license-beacon.js +1 -1
  61. package/lib/llm-pre-process.js +1 -1
  62. package/lib/msgpack.js +62 -0
  63. package/lib/oauth/decode-jwt-payload.js +39 -0
  64. package/lib/oauth/outlook-identity.js +61 -0
  65. package/lib/oauth/retry-setup.js +38 -0
  66. package/lib/oauth2-apps.js +10 -4
  67. package/lib/openapi/build-document.js +318 -0
  68. package/lib/openapi/index.js +95 -0
  69. package/lib/openapi/joi-schema.js +523 -0
  70. package/lib/outbox.js +66 -3
  71. package/lib/pre-process.js +1 -1
  72. package/lib/read-env-value.js +37 -0
  73. package/lib/routes-ui.js +5 -1
  74. package/lib/schemas.js +88 -17
  75. package/lib/swagger-options.js +173 -0
  76. package/lib/templates.js +1 -1
  77. package/lib/tokens.js +70 -6
  78. package/lib/tools.js +117 -48
  79. package/lib/totp.js +67 -0
  80. package/lib/ui-routes/account-routes.js +91 -15
  81. package/lib/ui-routes/admin-config-routes.js +2 -7
  82. package/lib/ui-routes/admin-entities-routes.js +3 -0
  83. package/lib/ui-routes/auth-routes.js +6 -24
  84. package/lib/ui-routes/dashboard-routes.js +2 -26
  85. package/lib/ui-routes/reference-routes.js +198 -0
  86. package/lib/ui-routes/route-helpers.js +39 -0
  87. package/lib/utils/is-email.js +34 -0
  88. package/lib/utils/to-camel-case.js +17 -0
  89. package/lib/webhook-egress.js +37 -0
  90. package/lib/webhooks.js +1 -1
  91. package/package.json +27 -31
  92. package/prepare-bundle-deps.sh +28 -0
  93. package/release-please-config.json +11 -0
  94. package/sbom.json +1 -1
  95. package/server.js +11 -3
  96. package/static/css/flyonui.css +1 -1
  97. package/static/css/public.css +3 -0
  98. package/static/css/src/app.tailwind.css +113 -0
  99. package/static/js/app.js +69 -0
  100. package/static/js/ee-client.js +238 -8
  101. package/static/js/reference.js +1021 -0
  102. package/static/js/ui.js +61 -33
  103. package/static/licenses.html +658 -1560
  104. package/translations/README.md +64 -0
  105. package/translations/de.mo +0 -0
  106. package/translations/de.po +164 -120
  107. package/translations/en.po +200 -161
  108. package/translations/et.mo +0 -0
  109. package/translations/et.po +163 -120
  110. package/translations/fr.mo +0 -0
  111. package/translations/fr.po +163 -120
  112. package/translations/ja.mo +0 -0
  113. package/translations/ja.po +163 -120
  114. package/translations/messages.pot +84 -54
  115. package/translations/nl.mo +0 -0
  116. package/translations/nl.po +164 -120
  117. package/translations/pl.mo +0 -0
  118. package/translations/pl.po +163 -120
  119. package/views/account-identity-error.hbs +34 -0
  120. package/views/accounts/edit.hbs +1 -0
  121. package/views/accounts/register/imap.hbs +12 -2
  122. package/views/config/ai.hbs +1 -1
  123. package/views/config/document-store/chat.hbs +5 -5
  124. package/views/config/document-store/index.hbs +2 -2
  125. package/views/config/document-store/pre-processing/index.hbs +1 -1
  126. package/views/config/email-processing.hbs +1 -1
  127. package/views/config/imap-proxy.hbs +1 -1
  128. package/views/config/license.hbs +1 -1
  129. package/views/config/oauth/index.hbs +3 -3
  130. package/views/config/security.hbs +1 -1
  131. package/views/config/smtp.hbs +2 -2
  132. package/views/dashboard.hbs +1 -1
  133. package/views/layout/app.hbs +43 -8
  134. package/views/oauth-scope-error.hbs +1 -1
  135. package/views/partials/oauth_form.hbs +4 -4
  136. package/views/partials/reference/anchor-link.hbs +20 -0
  137. package/views/partials/reference/disclosure.hbs +37 -0
  138. package/views/partials/reference/nav.hbs +120 -0
  139. package/views/partials/reference/operation.hbs +127 -0
  140. package/views/partials/reference/params.hbs +20 -0
  141. package/views/partials/reference/schema-node.hbs +99 -0
  142. package/views/partials/reference/schema.hbs +19 -0
  143. package/views/partials/reference/section-heading.hbs +16 -0
  144. package/views/partials/reference/token-alert.hbs +49 -0
  145. package/views/partials/reference/try-field.hbs +31 -0
  146. package/views/partials/reference/try-it.hbs +78 -0
  147. package/views/partials/side_menu.hbs +1 -1
  148. package/views/partials/ui/badge.hbs +4 -2
  149. package/views/partials/ui/page-header.hbs +1 -1
  150. package/views/partials/ui/search-input.hbs +31 -0
  151. package/views/partials/ui/setting-ref.hbs +1 -1
  152. package/views/partials/ui/stat-card.hbs +4 -2
  153. package/views/partials/ui/tab.hbs +6 -1
  154. package/views/partials/ui/tabs.hbs +2 -2
  155. package/views/reference/index.hbs +76 -0
  156. package/views/reference/redirect.hbs +49 -0
  157. package/views/reference/tag.hbs +28 -0
  158. package/views/reference/token.hbs +49 -0
  159. package/views/tokens/index.hbs +9 -1
  160. package/views/webhooks/index.hbs +3 -3
  161. package/workers/api.js +194 -302
  162. package/workers/imap.js +1 -1
  163. package/workers/submit.js +1 -1
  164. package/workers/webhooks.js +2 -13
  165. package/views/swagger/index.hbs +0 -82
package/lib/account.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  const logger = require('./logger');
4
4
  const Boom = require('@hapi/boom');
5
- const msgpack = require('msgpack5')();
5
+ const msgpack = require('./msgpack');
6
6
  const {
7
7
  normalizePath,
8
8
  formatAccountListingResponse,
@@ -10,6 +10,7 @@ const {
10
10
  mergeObjects,
11
11
  download,
12
12
  resolveCredentials,
13
+ useAuthServerForOAuth2,
13
14
  isEmail,
14
15
  resolveDelegatedAccount,
15
16
  escapeRedisGlob,
@@ -24,6 +25,7 @@ const settings = require('./settings');
24
25
  const { buildRetentionPolicy } = require('./queue-retention');
25
26
  const { isDocumentStoreEnabled, documentStoreFeatureEnabled } = require('./document-store');
26
27
  const redisScanDelete = require('./redis-scan-delete');
28
+ const outbox = require('./outbox');
27
29
  const { customAlphabet } = require('nanoid');
28
30
  const Lock = require('ioredfour');
29
31
  const { redis } = require('./db');
@@ -349,6 +351,13 @@ class Account {
349
351
  }
350
352
  break;
351
353
 
354
+ case 'expectedEmail':
355
+ // '' is the cleared marker written by serializeAccountData - report it as unset.
356
+ if (accountData[key]) {
357
+ result[key] = accountData[key];
358
+ }
359
+ break;
360
+
352
361
  case 'path':
353
362
  if (!accountData[key] || !accountData[key].length) {
354
363
  break;
@@ -651,6 +660,17 @@ class Account {
651
660
  }
652
661
  break;
653
662
 
663
+ case 'expectedEmail':
664
+ // Clearable, so it cannot ride the default branch: that drops nulls, and hmset only
665
+ // ever adds keys, which would leave an identity pin settable but never removable.
666
+ // Follows the same convention as `copy` above - null serializes to the empty marker
667
+ // and unserialize treats it as unset - rather than adding a per-field delete to
668
+ // persistUpdate.
669
+ if (typeof accountData[key] === 'string' || accountData[key] === null) {
670
+ result[key] = accountData[key] || '';
671
+ }
672
+ break;
673
+
654
674
  default:
655
675
  if (typeof accountData[key] !== 'undefined' && accountData[key] !== null && typeof accountData[key].toString === 'function') {
656
676
  result[key] = accountData[key].toString();
@@ -840,7 +860,15 @@ class Account {
840
860
  mergeObjects(accountData[subKey], oldAccountData[subKey]);
841
861
  }
842
862
 
843
- let pipeline = this.redis.multi().hmset(this.getAccountKey(), this.serializeAccountData(accountData));
863
+ // An update whose payload serializes to nothing - an empty request, say - must not reach hmset:
864
+ // Redis rejects a write with no field/value pairs outright ("wrong number of arguments"), which
865
+ // surfaced as a 500 on a perfectly valid request.
866
+ const updatedFields = this.serializeAccountData(accountData);
867
+
868
+ let pipeline = this.redis.multi();
869
+ if (Object.keys(updatedFields).length) {
870
+ pipeline = pipeline.hmset(this.getAccountKey(), updatedFields);
871
+ }
844
872
 
845
873
  if (addProvider && !LEGACY_KEYS.includes(addProvider)) {
846
874
  pipeline = pipeline.sadd(`${REDIS_PREFIX}oapp:a:${addProvider}`, this.account);
@@ -880,15 +908,13 @@ class Account {
880
908
  }
881
909
  }
882
910
 
883
- let [[err, result]] = await pipeline.exec();
884
- if (err) {
885
- throw err;
886
- }
887
-
888
- if (!result || result !== 'OK') {
889
- let message = 'Something went wrong';
890
- let error = Boom.boomify(new Error(message), { statusCode: 500 });
891
- throw error;
911
+ // Surface the first failing reply. Checked by scanning rather than by reading a fixed index: the
912
+ // hmset is now conditional, so a positional read would silently start asserting against whichever
913
+ // command happened to be queued first.
914
+ for (let [err] of (await pipeline.exec()) || []) {
915
+ if (err) {
916
+ throw err;
917
+ }
892
918
  }
893
919
 
894
920
  return oldAccountData;
@@ -1191,24 +1217,33 @@ class Account {
1191
1217
  const tombstoneTdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyTdy}`;
1192
1218
  const tombstoneYdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyYdy}`;
1193
1219
 
1220
+ // UNLINK rather than DEL throughout: none of these need the memory reclaimed synchronously,
1221
+ // and the outbox and the message ID index can hold enough entries that freeing them inline
1222
+ // would block Redis for every other worker.
1223
+ //
1224
+ // The outbox is read and unlinked in the same transaction, because that hash is the only
1225
+ // mapping from an account to the submit queue jobs of the messages it has not delivered
1226
+ // yet, and those jobs outlive the account otherwise. Reading it here means the ID list is
1227
+ // exactly what was unlinked, and costs no extra round trip.
1194
1228
  let pipeline = this.redis
1195
1229
  .multi()
1196
- .del(this.getAccountKey())
1230
+ .hkeys(`${REDIS_PREFIX}iaq:${this.account}`) // queued message IDs, removed from the submit queue below
1231
+ .unlink(this.getAccountKey())
1197
1232
  .srem(`${REDIS_PREFIX}ia:accounts`, this.account)
1198
- .del(this.getMailboxListKey()) // mailbox list
1199
- .del(this.getMailboxHashKey()) // mailbox list for ID references
1200
- .del(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce list
1201
- .del(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
1202
- .del(`${REDIS_PREFIX}iaq:${this.account}`) // delayed message queue
1203
- .del(`${REDIS_PREFIX}iat:${this.account}`) // access tokens
1204
- .del(`${REDIS_PREFIX}iac:${this.account}`) // cache hash
1205
- .del(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
1233
+ .unlink(this.getMailboxListKey()) // mailbox list
1234
+ .unlink(this.getMailboxHashKey()) // mailbox list for ID references
1235
+ .unlink(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce list
1236
+ .unlink(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
1237
+ .unlink(`${REDIS_PREFIX}iaq:${this.account}`) // delayed message queue
1238
+ .unlink(`${REDIS_PREFIX}iat:${this.account}`) // access tokens
1239
+ .unlink(`${REDIS_PREFIX}iac:${this.account}`) // cache hash
1240
+ .unlink(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
1206
1241
 
1207
- .del(tombstoneTdy)
1208
- .del(tombstoneYdy)
1242
+ .unlink(tombstoneTdy)
1243
+ .unlink(tombstoneYdy)
1209
1244
 
1210
- .del(`${REDIS_PREFIX}tpl:${this.account}:i`) // stored templates index
1211
- .del(`${REDIS_PREFIX}tpl:${this.account}:c`); // stored templates index
1245
+ .unlink(`${REDIS_PREFIX}tpl:${this.account}:i`) // stored templates index
1246
+ .unlink(`${REDIS_PREFIX}tpl:${this.account}:c`); // stored templates index
1212
1247
 
1213
1248
  if (accountData.oauth2?.provider) {
1214
1249
  pipeline = pipeline.srem(`${REDIS_PREFIX}oapp:a:${accountData.oauth2.provider}`, this.account);
@@ -1219,11 +1254,25 @@ class Account {
1219
1254
 
1220
1255
  let result = await pipeline.exec();
1221
1256
 
1257
+ // Results are positional: [0] is the outbox HKEYS, [1] the account key UNLINK. Both indexes
1258
+ // move if a command is inserted ahead of them.
1259
+ let queuedMessageIds = (result && result[0] && result[0][1]) || [];
1260
+ if (queuedMessageIds.length) {
1261
+ // Best effort: the account is already gone, so a queue that will not cooperate must not
1262
+ // turn a completed deletion into an error.
1263
+ try {
1264
+ let removed = await outbox.removeJobs(queuedMessageIds, { account: this.account, logger: this.logger });
1265
+ this.logger.info({ msg: 'Removed queued messages of a deleted account', account: this.account, queued: queuedMessageIds.length, removed });
1266
+ } catch (err) {
1267
+ this.logger.error({ msg: 'Failed to remove queued messages of a deleted account', account: this.account, err });
1268
+ }
1269
+ }
1270
+
1222
1271
  // scan and delete keys
1223
1272
  // should we wait though? might take a lot of time
1224
1273
  await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
1225
1274
 
1226
- if (!result || !result[0] || !result[0][1]) {
1275
+ if (!result || !result[1] || !result[1][1]) {
1227
1276
  return {
1228
1277
  account: this.account,
1229
1278
  deleted: false
@@ -2767,7 +2816,7 @@ class Account {
2767
2816
  throw error;
2768
2817
  }
2769
2818
 
2770
- if (accountData.oauth2.useAuthServer) {
2819
+ if (await useAuthServerForOAuth2(accountData.oauth2, this.logger, { account: this.account, target: 'api' })) {
2771
2820
  // resolve credentials
2772
2821
 
2773
2822
  let authData = await resolveCredentials(this.account, 'api');
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ // The local-address selection strategies, shared by the joi schemas (which use the keys as
4
+ // the allowed value set), the admin UI (which shows the titles), and lib/enum-descriptions.js
5
+ // (which documents each value in the API reference). One table so a new strategy cannot be
6
+ // half-added.
7
+
8
+ const ADDRESS_STRATEGIES = [
9
+ { key: 'default', title: 'Default', description: 'Let the operating system pick the source address' },
10
+ {
11
+ key: 'dedicated',
12
+ title: 'Dedicated',
13
+ description: 'Reuse the same local address for an account, so the remote server sees a stable IP'
14
+ },
15
+ { key: 'random', title: 'Random', description: 'Pick a random local address for every connection' }
16
+ ];
17
+
18
+ module.exports = { ADDRESS_STRATEGIES };
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+
3
+ // Ready-to-run request samples for an operation. Generated per request because the
4
+ // base URL comes from the request the reference page was loaded with, so an instance
5
+ // behind a proxy shows the address the caller actually reaches it on.
6
+ //
7
+ // Samples are illustrative: path parameters are filled from their schema examples and
8
+ // only required query parameters are included, so the snippet is runnable after
9
+ // swapping in a real account id and access token.
10
+
11
+ // All three samples read the token from the same environment variable so the page can
12
+ // document it once and the snippets stay copy-paste runnable without editing them.
13
+ const TOKEN_ENV_VAR = 'EMAILENGINE_TOKEN';
14
+
15
+ const INDENT = ' ';
16
+
17
+ function buildUrl(baseUrl, operation) {
18
+ let path = operation.path;
19
+
20
+ for (const parameter of operation.pathParams) {
21
+ path = path.replace(`{${parameter.name}}`, encodeURIComponent(parameter.sampleValue));
22
+ }
23
+
24
+ const query = operation.queryParams
25
+ .filter(parameter => parameter.required)
26
+ .map(parameter => `${encodeURIComponent(parameter.name)}=${encodeURIComponent(parameter.sampleValue)}`);
27
+
28
+ return `${baseUrl}${path}${query.length ? `?${query.join('&')}` : ''}`;
29
+ }
30
+
31
+ // Single-quoted shell strings cannot contain a single quote, so each one closes the
32
+ // string, adds an escaped quote and reopens it.
33
+ function shellQuote(value) {
34
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
35
+ }
36
+
37
+ function curlSample(url, operation, bodyJson) {
38
+ const lines = [`curl -X ${operation.methodLabel} ${shellQuote(url)} \\`, `${INDENT}-H "Authorization: Bearer $${TOKEN_ENV_VAR}"`];
39
+
40
+ if (bodyJson) {
41
+ lines[lines.length - 1] += ' \\';
42
+ lines.push(`${INDENT}-H "Content-Type: application/json" \\`);
43
+ lines.push(`${INDENT}-d ${shellQuote(bodyJson)}`);
44
+ }
45
+
46
+ return lines.join('\n');
47
+ }
48
+
49
+ function nodeSample(url, operation, bodyJson) {
50
+ const lines = [
51
+ `const response = await fetch(${JSON.stringify(url)}, {`,
52
+ `${INDENT}method: ${JSON.stringify(operation.methodLabel)},`,
53
+ `${INDENT}headers: {`
54
+ ];
55
+
56
+ const headers = [`${INDENT}${INDENT}Authorization: \`Bearer \${accessToken}\``];
57
+ if (bodyJson) {
58
+ headers.push(`${INDENT}${INDENT}'Content-Type': 'application/json'`);
59
+ }
60
+ lines.push(headers.join(',\n'));
61
+ lines.push(`${INDENT}}${bodyJson ? ',' : ''}`);
62
+
63
+ if (bodyJson) {
64
+ const body = bodyJson
65
+ .split('\n')
66
+ .map((line, index) => (index === 0 ? line : `${INDENT}${line}`))
67
+ .join('\n');
68
+ lines.push(`${INDENT}body: JSON.stringify(${body})`);
69
+ }
70
+
71
+ lines.push('});');
72
+ lines.push('');
73
+ lines.push('const data = await response.json();');
74
+
75
+ return `const accessToken = process.env.${TOKEN_ENV_VAR};\n\n${lines.join('\n')}`;
76
+ }
77
+
78
+ // JSON literals do not survive a paste into Python (true/false/null), so the example
79
+ // value is re-emitted with Python literals instead of string-replacing the JSON.
80
+ function pythonLiteral(value, indent) {
81
+ const pad = INDENT.repeat(indent);
82
+ const padInner = INDENT.repeat(indent + 1);
83
+
84
+ if (value === null) {
85
+ return 'None';
86
+ }
87
+
88
+ if (Array.isArray(value)) {
89
+ if (!value.length) {
90
+ return '[]';
91
+ }
92
+ const items = value.map(item => `${padInner}${pythonLiteral(item, indent + 1)}`);
93
+ return `[\n${items.join(',\n')}\n${pad}]`;
94
+ }
95
+
96
+ switch (typeof value) {
97
+ case 'boolean':
98
+ return value ? 'True' : 'False';
99
+ case 'number':
100
+ return String(value);
101
+ case 'object': {
102
+ const keys = Object.keys(value);
103
+ if (!keys.length) {
104
+ return '{}';
105
+ }
106
+ const entries = keys.map(key => `${padInner}${JSON.stringify(key)}: ${pythonLiteral(value[key], indent + 1)}`);
107
+ return `{\n${entries.join(',\n')}\n${pad}}`;
108
+ }
109
+ default:
110
+ return JSON.stringify(String(value));
111
+ }
112
+ }
113
+
114
+ function pythonSample(url, operation, bodyValue) {
115
+ const lines = ['import os', 'import requests', '', `access_token = os.environ["${TOKEN_ENV_VAR}"]`, ''];
116
+
117
+ const args = [`${INDENT}${JSON.stringify(url)},`, `${INDENT}headers={"Authorization": f"Bearer {access_token}"},`];
118
+
119
+ if (typeof bodyValue !== 'undefined') {
120
+ args.push(`${INDENT}json=${pythonLiteral(bodyValue, 1)},`);
121
+ }
122
+
123
+ lines.push(`response = requests.${operation.method}(`);
124
+ lines.push(args.join('\n'));
125
+ lines.push(')');
126
+ lines.push('');
127
+ lines.push('print(response.json())');
128
+
129
+ return lines.join('\n');
130
+ }
131
+
132
+ // A hljs class has to be a bare token, and `lang` is free text from the document. Kept to
133
+ // the characters real language names use (c++, c#, objective-c, shell-session) so nothing
134
+ // else can end up in the class attribute.
135
+ function highlightLanguage(lang) {
136
+ return String(lang)
137
+ .toLowerCase()
138
+ .replace(/[^a-z0-9+#._-]/g, '');
139
+ }
140
+
141
+ // Hand-written samples from an operation's `x-codeSamples` extension - the de-facto
142
+ // standard for this, read by Redoc and Scalar too. A route declares them in its
143
+ // `plugins.openapi` block, and lib/openapi/ publishes any `x-*` key verbatim, so they reach
144
+ // every consumer of /swagger.json rather than only this page.
145
+ //
146
+ // Only the current spelling is accepted. Redoc's older `x-code-samples` exists in documents
147
+ // written by hand or by other tools; ours is generated in-house from the route table, so it
148
+ // can only ever contain what our own routes declare.
149
+ //
150
+ // Entries that are not `{ lang, source }` are dropped rather than rendered as blanks: the
151
+ // extension is free-form, and a malformed one should cost its own tab, not the page.
152
+ //
153
+ // Normalized once when the model is built, since nothing here depends on the request.
154
+ function readCodeSamples(specOperation) {
155
+ const declared = specOperation['x-codeSamples'];
156
+
157
+ if (!Array.isArray(declared)) {
158
+ return [];
159
+ }
160
+
161
+ return declared
162
+ .filter(sample => sample && typeof sample.lang === 'string' && typeof sample.source === 'string')
163
+ .map((sample, index) => ({
164
+ id: `custom-${index}`,
165
+ label: typeof sample.label === 'string' && sample.label ? sample.label : sample.lang,
166
+ language: highlightLanguage(sample.lang),
167
+ code: sample.source
168
+ }));
169
+ }
170
+
171
+ // Returns the tab set rendered under an operation. `bodyValue` is the synthesized
172
+ // request example (undefined for operations with no request body).
173
+ //
174
+ // Hand-written samples come first: someone wrote one for this operation because the
175
+ // synthesized snippets did not tell the story, which only works if it is the tab that
176
+ // opens.
177
+ function buildCodeSamples(operation, baseUrl, bodyValue, bodyJson) {
178
+ const url = buildUrl(baseUrl, operation);
179
+
180
+ return [
181
+ ...(operation.codeSamples || []),
182
+ { id: 'curl', label: 'curl', language: 'bash', code: curlSample(url, operation, bodyJson) },
183
+ { id: 'node', label: 'Node.js', language: 'javascript', code: nodeSample(url, operation, bodyJson) },
184
+ { id: 'python', label: 'Python', language: 'python', code: pythonSample(url, operation, bodyValue) }
185
+ // Tab ids are composed here for the same reason as the response tabs: ui/tabs
186
+ // neutralizes its hash params inside the partial block, so the operation id is
187
+ // not reachable from the template
188
+ ].map((sample, index) => Object.assign({}, sample, { tabId: `${operation.id}-sample-${sample.id}`, active: index === 0 }));
189
+ }
190
+
191
+ module.exports = {
192
+ buildCodeSamples,
193
+ readCodeSamples
194
+ };
@@ -0,0 +1,193 @@
1
+ 'use strict';
2
+
3
+ // Text and value formatting helpers for the server-rendered API reference.
4
+ //
5
+ // Everything here is pure and spec-free, so it can be unit tested in isolation. Anything
6
+ // that has to follow a $ref (type labels) lives in schema-tree.js, which owns resolution.
7
+ //
8
+ // SECURITY: this module is the single place where reference text becomes HTML. The
9
+ // OpenAPI document is generated from our own joi schemas, so the strings are not
10
+ // attacker controlled, but three descriptions legitimately contain angle brackets
11
+ // (`templateHtmlHead` documents injecting into the `<head>` section) and must render
12
+ // as literal text. formatDescription() therefore escapes first and only then adds a
13
+ // fixed, closed set of tags back. Never reverse that order and never widen the tag
14
+ // set to pass markup through.
15
+ //
16
+ // Note on `marked`: the repo already renders markdown with it (the EULA page), but it
17
+ // is deliberately not used here - the escape-first ordering is the security property,
18
+ // and marked would need separate sanitization to give the same guarantee.
19
+
20
+ const he = require('he');
21
+
22
+ // Only http(s) targets become links. The input is already HTML-escaped when this runs,
23
+ // but escaping does not neutralize a `javascript:` scheme in an href, so the scheme is
24
+ // checked explicitly rather than relying on the escape pass.
25
+ function isSafeUrl(url) {
26
+ return /^https?:\/\//i.test(url);
27
+ }
28
+
29
+ // Minimal inline formatter for schema and operation descriptions. Handles the small
30
+ // subset of markdown our joi `.description()` strings actually use: backtick code
31
+ // spans, `[label](url)` links, bare URLs, and paragraph breaks. Input is escaped
32
+ // first, so the only tags in the output are the ones added here.
33
+ function formatDescription(text) {
34
+ if (!text) {
35
+ return '';
36
+ }
37
+
38
+ let html = he.escape(String(text));
39
+
40
+ // he.escape() escapes the backtick too (to `&#x60;`, for an old IE attribute quirk),
41
+ // so the code-span pass has to match the escaped form - it runs after escaping by
42
+ // design and there are no literal backticks left to find.
43
+ html = html.replace(/&#x60;([\s\S]+?)&#x60;/g, (match, code) => `<code class="ee-code">${code}</code>`);
44
+
45
+ html = html.replace(/\[([^\]]+)\]\(([^\s)]+)\)/g, (match, label, url) => {
46
+ if (!isSafeUrl(url)) {
47
+ return match;
48
+ }
49
+ return `<a href="${url}" target="_blank" rel="noopener noreferrer" class="link link-primary">${label}</a>`;
50
+ });
51
+
52
+ // Bare URLs, skipping ones already inside an href="..." emitted above
53
+ html = html.replace(/(^|[\s(])(https?:\/\/[^\s<>"')]+)/g, (match, prefix, url) => {
54
+ return `${prefix}<a href="${url}" target="_blank" rel="noopener noreferrer" class="link link-primary">${url}</a>`;
55
+ });
56
+
57
+ return html
58
+ .split(/\n{2,}/)
59
+ .map(paragraph => paragraph.replace(/\n/g, '<br>'))
60
+ .join('</p><p class="mt-2">');
61
+ }
62
+
63
+ // URL segment for a tag name: "Export (Beta)" -> "export-beta"
64
+ function slugify(value) {
65
+ return String(value || '')
66
+ .toLowerCase()
67
+ .replace(/[^a-z0-9]+/g, '-')
68
+ .replace(/^-+|-+$/g, '');
69
+ }
70
+
71
+ // Where a group and an operation live. Four surfaces link to them - the tag directory, the
72
+ // nav's group rows, its per-group lists and the filter index - so the shape of a reference
73
+ // link is stated here rather than composed at each of them. The route itself is registered in
74
+ // lib/ui-routes/reference-routes.js.
75
+ function tagUrl(tagSlug) {
76
+ return `/admin/reference/${tagSlug}`;
77
+ }
78
+
79
+ function operationUrl(tagSlug, operationId) {
80
+ return `${tagUrl(tagSlug)}#${operationId}`;
81
+ }
82
+
83
+ const METHOD_VARIANTS = {
84
+ get: 'info',
85
+ post: 'success',
86
+ put: 'warning',
87
+ patch: 'warning',
88
+ delete: 'error'
89
+ };
90
+
91
+ function methodVariant(method) {
92
+ return METHOD_VARIANTS[String(method || '').toLowerCase()] || 'neutral';
93
+ }
94
+
95
+ // "1 to 10 items" / "min 1 item" / "max 10 items", or null when neither bound is set.
96
+ function rangeChip(min, max, unit) {
97
+ const suffix = unit ? ` ${unit}` : '';
98
+
99
+ if (typeof min === 'number' && typeof max === 'number') {
100
+ return `${min} to ${max}${suffix}`;
101
+ }
102
+ if (typeof min === 'number') {
103
+ return `min ${min}${suffix}`;
104
+ }
105
+ if (typeof max === 'number') {
106
+ return `max ${max}${suffix}`;
107
+ }
108
+ return null;
109
+ }
110
+
111
+ // Short constraint chips shown next to a property. Covers both the standard OpenAPI
112
+ // keywords and the `x-*` extensions the generator emits for joi rules OpenAPI has no
113
+ // keyword for (accepted URI schemes, email format, value coercion) - real validation
114
+ // rules that generic documentation tools drop on the floor.
115
+ function constraintList(schema) {
116
+ if (!schema || typeof schema !== 'object') {
117
+ return [];
118
+ }
119
+
120
+ const chips = [];
121
+
122
+ if (schema.format) {
123
+ chips.push(schema.format);
124
+ }
125
+
126
+ for (const chip of [
127
+ rangeChip(schema.minimum, schema.maximum, ''),
128
+ rangeChip(schema.minLength, schema.maxLength, 'chars'),
129
+ rangeChip(schema.minItems, schema.maxItems, 'items')
130
+ ]) {
131
+ if (chip) {
132
+ chips.push(chip);
133
+ }
134
+ }
135
+
136
+ if (schema.pattern) {
137
+ chips.push(`pattern ${schema.pattern}`);
138
+ }
139
+
140
+ const xFormat = schema['x-format'];
141
+ if (xFormat && typeof xFormat === 'object') {
142
+ for (const key of Object.keys(xFormat)) {
143
+ const value = xFormat[key];
144
+ if (key === 'uri' && value && Array.isArray(value.scheme) && value.scheme.length) {
145
+ chips.push(`URI (${value.scheme.join(', ')})`);
146
+ } else {
147
+ chips.push(key);
148
+ }
149
+ }
150
+ }
151
+
152
+ const xConvert = schema['x-convert'];
153
+ if (xConvert && typeof xConvert === 'object') {
154
+ if (xConvert.trim) {
155
+ chips.push('trimmed');
156
+ }
157
+ if (xConvert.case === 'lower') {
158
+ chips.push('lowercased');
159
+ }
160
+ if (xConvert.case === 'upper') {
161
+ chips.push('uppercased');
162
+ }
163
+ }
164
+
165
+ if (schema['x-constraint'] && schema['x-constraint'].single) {
166
+ chips.push('single value allowed');
167
+ }
168
+
169
+ return chips;
170
+ }
171
+
172
+ // JSON rendered for the example panels. Kept here so the pretty-printing is identical
173
+ // everywhere (page body, code samples, try-it request editor).
174
+ function stringifyExample(value) {
175
+ if (typeof value === 'undefined') {
176
+ return '';
177
+ }
178
+ try {
179
+ return JSON.stringify(value, null, 2);
180
+ } catch (err) {
181
+ return '';
182
+ }
183
+ }
184
+
185
+ module.exports = {
186
+ formatDescription,
187
+ slugify,
188
+ tagUrl,
189
+ operationUrl,
190
+ methodVariant,
191
+ constraintList,
192
+ stringifyExample
193
+ };