@sasjs/api 0.18.1 → 0.19.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 (48) hide show
  1. package/build/browser.js +711 -14
  2. package/build/cjs/admin/service.js +209 -0
  3. package/build/cjs/authconfig/service.js +139 -0
  4. package/build/cjs/corpus/admin.js +101 -0
  5. package/build/cjs/corpus/authconfig.js +47 -0
  6. package/build/cjs/corpus/directory.js +31 -0
  7. package/build/cjs/corpus/runner.js +13 -0
  8. package/build/cjs/directory/service.js +116 -0
  9. package/build/cjs/host/dispatch.js +39 -0
  10. package/build/cjs/identity/memory-store.js +4 -1
  11. package/build/cjs/index.js +8 -2
  12. package/build/cjs/routes/generated.js +56 -0
  13. package/build/cjs/routes/overlay.js +86 -12
  14. package/build/esm/admin/service.d.ts +123 -0
  15. package/build/esm/admin/service.d.ts.map +1 -0
  16. package/build/esm/admin/service.js +201 -0
  17. package/build/esm/authconfig/service.d.ts +92 -0
  18. package/build/esm/authconfig/service.d.ts.map +1 -0
  19. package/build/esm/authconfig/service.js +134 -0
  20. package/build/esm/corpus/admin.d.ts +22 -0
  21. package/build/esm/corpus/admin.d.ts.map +1 -0
  22. package/build/esm/corpus/admin.js +98 -0
  23. package/build/esm/corpus/authconfig.d.ts +31 -0
  24. package/build/esm/corpus/authconfig.d.ts.map +1 -0
  25. package/build/esm/corpus/authconfig.js +44 -0
  26. package/build/esm/corpus/directory.d.ts +20 -0
  27. package/build/esm/corpus/directory.d.ts.map +1 -0
  28. package/build/esm/corpus/directory.js +28 -0
  29. package/build/esm/corpus/runner.d.ts.map +1 -1
  30. package/build/esm/corpus/runner.js +13 -0
  31. package/build/esm/directory/service.d.ts +71 -0
  32. package/build/esm/directory/service.d.ts.map +1 -0
  33. package/build/esm/directory/service.js +112 -0
  34. package/build/esm/host/dispatch.d.ts +18 -0
  35. package/build/esm/host/dispatch.d.ts.map +1 -1
  36. package/build/esm/host/dispatch.js +39 -0
  37. package/build/esm/identity/memory-store.d.ts.map +1 -1
  38. package/build/esm/identity/memory-store.js +4 -1
  39. package/build/esm/identity/types.d.ts +5 -0
  40. package/build/esm/identity/types.d.ts.map +1 -1
  41. package/build/esm/index.d.ts +3 -0
  42. package/build/esm/index.d.ts.map +1 -1
  43. package/build/esm/index.js +3 -0
  44. package/build/esm/routes/generated.d.ts.map +1 -1
  45. package/build/esm/routes/generated.js +56 -0
  46. package/build/esm/routes/overlay.d.ts.map +1 -1
  47. package/build/esm/routes/overlay.js +86 -12
  48. package/package.json +1 -1
@@ -194,6 +194,40 @@ const dispatch = async (services, routeId, request = {}) => {
194
194
  throw new types_js_1.ApiError(501, `This host has no info service, so it cannot answer ${routeId}.`);
195
195
  return { status: 200, body: await services.info.info() };
196
196
  }
197
+ // ------------------------------------------------- a host's own reports
198
+ //
199
+ // The administrator middleware is the host's (sasjs/server mounts
200
+ // authenticateAccessToken and verifyAdmin ahead of all of these), which is
201
+ // why their 401 is marked host-only in the overlay. The package answers a
202
+ // body, and for a log tail the refusals that belong to the name rule.
203
+ case 'GET /SASjsApi/admin/diagnostics': {
204
+ if (!services.admin)
205
+ throw new types_js_1.ApiError(501, `This host has no admin service, so it cannot answer ${routeId}.`);
206
+ return { status: 200, body: await services.admin.diagnostics() };
207
+ }
208
+ case 'GET /SASjsApi/admin/logs': {
209
+ if (!services.admin)
210
+ throw new types_js_1.ApiError(501, `This host has no admin service, so it cannot answer ${routeId}.`);
211
+ return { status: 200, body: { files: await services.admin.logs() } };
212
+ }
213
+ case 'GET /SASjsApi/admin/logs/{fileName}': {
214
+ if (!services.admin)
215
+ throw new types_js_1.ApiError(501, `This host has no admin service, so it cannot answer ${routeId}.`);
216
+ return {
217
+ status: 200,
218
+ body: await services.admin.logTail(String(params.fileName ?? ''), query.lines)
219
+ };
220
+ }
221
+ case 'GET /SASjsApi/authConfig': {
222
+ if (!services.authConfig)
223
+ throw new types_js_1.ApiError(501, `This host has no auth-config service, so it cannot answer ${routeId}.`);
224
+ return { status: 200, body: await services.authConfig.authConfig() };
225
+ }
226
+ case 'POST /SASjsApi/authConfig/synchroniseWithLDAP': {
227
+ if (!services.directory)
228
+ throw new types_js_1.ApiError(501, `This host has no directory service, so it cannot answer ${routeId}.`);
229
+ return { status: 200, body: await services.directory.synchronise() };
230
+ }
197
231
  case 'GET /SASjsApi/drive/file': {
198
232
  const file = await drive.read(String(query._filePath || ''));
199
233
  return { status: 200, contents: file.contents };
@@ -518,6 +552,11 @@ exports.dispatch = dispatch;
518
552
  /** Whether a route is one `dispatch` can answer today. */
519
553
  exports.HANDLED_ROUTES = [
520
554
  'GET /SASjsApi/info',
555
+ 'GET /SASjsApi/admin/diagnostics',
556
+ 'GET /SASjsApi/admin/logs',
557
+ 'GET /SASjsApi/admin/logs/{fileName}',
558
+ 'GET /SASjsApi/authConfig',
559
+ 'POST /SASjsApi/authConfig/synchroniseWithLDAP',
521
560
  'POST /SASjsApi/drive/deploy/upload',
522
561
  'DELETE /SASjsApi/drive/deploy',
523
562
  'GET /SASjsApi/stp/execute',
@@ -310,7 +310,10 @@ class MemoryIdentityStore {
310
310
  name: input.name,
311
311
  description: input.description,
312
312
  isActive: input.isActive,
313
- users: []
313
+ users: [],
314
+ ...(input.authProvider === undefined
315
+ ? {}
316
+ : { authProvider: input.authProvider })
314
317
  };
315
318
  this.groupList.set(group.uid, group);
316
319
  return group;
@@ -14,8 +14,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.ADMIN_SIGNED_IN = exports.RECORD_CORPUS = exports.unpublishAppStream = exports.MemoryAppStreamRegistry = exports.RUNTIME_CORPUS = exports.MemorySessionRunner = exports.createRuntimeService = exports.DOCUMENTED_RUN_TIMES = exports.CODE_DEBUG = exports.MemorySessionHost = exports.DEFAULT_SESSIONS = exports.createSessionService = exports.SESSION_CORPUS = exports.DEPLOY_CORPUS = exports.IDENTITY_CORPUS = exports.DRIVE_CORPUS = exports.parseIdentity = exports.IDENTITY_FORMAT = exports.DEFAULT_IDENTITY = exports.MemoryIdentityStore = exports.normaliseInfo = exports.createInfoService = exports.BROWSER_INFO = exports.INFO_CORPUS = exports.CODE_CORPUS = exports.sanitiseDisplayName = exports.createRecordService = exports.createIdentityService = exports.HANDLED_ROUTES = exports.dispatch = exports.TAG_CAPABILITIES = exports.OVERLAY = exports.findRoute = exports.routeById = exports.ROUTES = exports.MemoryDriveStore = exports.measureDeployTree = exports.isDeployTree = exports.deployTree = exports.decodeBase64 = exports.checkDeployTree = exports.DEPLOY_SUCCESS = exports.DEPLOY_PAYLOAD_BYTES = exports.DEPLOY_LIMITS = exports.createDriveService = exports.isRoot = exports.basename = exports.dirname = exports.hasBlockedExtension = exports.normaliseDrivePath = void 0;
18
- exports.servicesFor = exports.runCase = exports.PROVIDER_MANAGED = void 0;
17
+ exports.MemoryAppStreamRegistry = exports.RUNTIME_CORPUS = exports.MemorySessionRunner = exports.createRuntimeService = exports.DOCUMENTED_RUN_TIMES = exports.CODE_DEBUG = exports.MemorySessionHost = exports.DEFAULT_SESSIONS = exports.createSessionService = exports.SESSION_CORPUS = exports.DEPLOY_CORPUS = exports.IDENTITY_CORPUS = exports.DRIVE_CORPUS = exports.parseIdentity = exports.IDENTITY_FORMAT = exports.DEFAULT_IDENTITY = exports.MemoryIdentityStore = exports.normaliseInfo = exports.createInfoService = exports.BROWSER_INFO = exports.DIRECTORY_CORPUS = exports.AUTH_CONFIG_CORPUS = exports.ADMIN_CORPUS = exports.INFO_CORPUS = exports.CODE_CORPUS = exports.sanitiseDisplayName = exports.createRecordService = exports.createIdentityService = exports.HANDLED_ROUTES = exports.dispatch = exports.TAG_CAPABILITIES = exports.OVERLAY = exports.findRoute = exports.routeById = exports.ROUTES = exports.MemoryDriveStore = exports.measureDeployTree = exports.isDeployTree = exports.deployTree = exports.decodeBase64 = exports.checkDeployTree = exports.DEPLOY_SUCCESS = exports.DEPLOY_PAYLOAD_BYTES = exports.DEPLOY_LIMITS = exports.createDriveService = exports.isRoot = exports.basename = exports.dirname = exports.hasBlockedExtension = exports.normaliseDrivePath = void 0;
18
+ exports.servicesFor = exports.runCase = exports.PROVIDER_MANAGED = exports.ADMIN_SIGNED_IN = exports.RECORD_CORPUS = exports.unpublishAppStream = void 0;
19
19
  /**
20
20
  * `@sasjs/api` - the SASjs Server API described once.
21
21
  *
@@ -72,6 +72,12 @@ var code_js_1 = require("./corpus/code.js");
72
72
  Object.defineProperty(exports, "CODE_CORPUS", { enumerable: true, get: function () { return code_js_1.CODE_CORPUS; } });
73
73
  var info_js_1 = require("./corpus/info.js");
74
74
  Object.defineProperty(exports, "INFO_CORPUS", { enumerable: true, get: function () { return info_js_1.INFO_CORPUS; } });
75
+ var admin_js_1 = require("./corpus/admin.js");
76
+ Object.defineProperty(exports, "ADMIN_CORPUS", { enumerable: true, get: function () { return admin_js_1.ADMIN_CORPUS; } });
77
+ var authconfig_js_1 = require("./corpus/authconfig.js");
78
+ Object.defineProperty(exports, "AUTH_CONFIG_CORPUS", { enumerable: true, get: function () { return authconfig_js_1.AUTH_CONFIG_CORPUS; } });
79
+ var directory_js_1 = require("./corpus/directory.js");
80
+ Object.defineProperty(exports, "DIRECTORY_CORPUS", { enumerable: true, get: function () { return directory_js_1.DIRECTORY_CORPUS; } });
75
81
  var service_js_3 = require("./info/service.js");
76
82
  Object.defineProperty(exports, "BROWSER_INFO", { enumerable: true, get: function () { return service_js_3.BROWSER_INFO; } });
77
83
  Object.defineProperty(exports, "createInfoService", { enumerable: true, get: function () { return service_js_3.createInfoService; } });
@@ -29,6 +29,14 @@ exports.GENERATED_ROUTES = [
29
29
  {
30
30
  status: 200,
31
31
  description: 'Ok'
32
+ },
33
+ {
34
+ status: 401,
35
+ description: 'Unauthorized, or an administrator account is required. The mount point in routes/api/index.ts applies both checks before this handler runs.'
36
+ },
37
+ {
38
+ status: 500,
39
+ description: 'The diagnostics could not be read'
32
40
  }
33
41
  ]
34
42
  },
@@ -44,6 +52,14 @@ exports.GENERATED_ROUTES = [
44
52
  {
45
53
  status: 200,
46
54
  description: 'Ok'
55
+ },
56
+ {
57
+ status: 401,
58
+ description: 'Unauthorized, or an administrator account is required. The mount point in routes/api/index.ts applies both checks before this handler runs.'
59
+ },
60
+ {
61
+ status: 500,
62
+ description: 'The log folder could not be listed'
47
63
  }
48
64
  ]
49
65
  },
@@ -72,6 +88,22 @@ exports.GENERATED_ROUTES = [
72
88
  {
73
89
  status: 200,
74
90
  description: 'Ok'
91
+ },
92
+ {
93
+ status: 400,
94
+ description: 'Invalid log file name.'
95
+ },
96
+ {
97
+ status: 401,
98
+ description: 'Unauthorized, or an administrator account is required. The mount point in routes/api/index.ts applies both checks before this handler runs.'
99
+ },
100
+ {
101
+ status: 404,
102
+ description: 'Log file not found.'
103
+ },
104
+ {
105
+ status: 500,
106
+ description: 'The log file could not be read'
75
107
  }
76
108
  ]
77
109
  },
@@ -209,6 +241,18 @@ exports.GENERATED_ROUTES = [
209
241
  {
210
242
  status: 200,
211
243
  description: 'Ok'
244
+ },
245
+ {
246
+ status: 401,
247
+ description: 'Unauthorized, or an administrator account is required. The mount point in routes/api/index.ts applies both checks before this handler runs.'
248
+ },
249
+ {
250
+ status: 403,
251
+ description: 'Not Allowed while in Desktop Mode.'
252
+ },
253
+ {
254
+ status: 500,
255
+ description: 'The provider configuration could not be read'
212
256
  }
213
257
  ]
214
258
  },
@@ -224,6 +268,18 @@ exports.GENERATED_ROUTES = [
224
268
  {
225
269
  status: 200,
226
270
  description: 'Ok'
271
+ },
272
+ {
273
+ status: 401,
274
+ description: 'Unauthorized, or an administrator account is required. The mount point in routes/api/index.ts applies both checks before this handler runs.'
275
+ },
276
+ {
277
+ status: 403,
278
+ description: 'Not Allowed while in Desktop Mode.'
279
+ },
280
+ {
281
+ status: 500,
282
+ description: 'The directory could not be synchronised'
227
283
  }
228
284
  ]
229
285
  },
@@ -25,9 +25,6 @@ exports.TAG_CAPABILITIES = {
25
25
  * operation waits on, and thirty copies of the same sentence would say the same
26
26
  * thing thirty times.
27
27
  */
28
- const DIRECTORY = 'Synchronising with an external auth provider needs a directory port, which this package does not have: a host decides which directory it holds accounts in, and answers this itself.';
29
- const HOST_CONFIG = "The body is the host's own provider configuration - the directory URL, bind DN and which secrets are set - which a mock states for itself and this package cannot know.";
30
- const HOST_OWNED = "The host owns this report: it describes the host's own process and files, which a browser build has no equivalent of.";
31
28
  const WEB_BUNDLE = 'The host serves its own web bundle; there is no API decision here for this package to answer.';
32
29
  const success = { status: 'success' };
33
30
  const user = {
@@ -56,12 +53,71 @@ exports.OVERLAY = {
56
53
  hostResponses: [500],
57
54
  responses: { 200: 'OK!' }
58
55
  },
59
- // Admin - the host's own process and files
60
- 'GET /SASjsApi/admin/diagnostics': { implemented: false, reason: HOST_OWNED },
61
- 'GET /SASjsApi/admin/logs': { implemented: false, reason: HOST_OWNED },
56
+ // Admin - the host's own process and files, over the reports it supplies.
57
+ // The administrator check is the host's mount point (sasjs/server puts
58
+ // authenticateAccessToken and verifyAdmin in front of all three), so its 401
59
+ // - and the 500 a genuine failure answers - are host-only statuses.
60
+ 'GET /SASjsApi/admin/diagnostics': {
61
+ implemented: true,
62
+ hostResponses: [401, 500],
63
+ responses: {
64
+ 200: {
65
+ build: { version: '', gitHash: '', buildDate: null },
66
+ server: {
67
+ mode: 'desktop',
68
+ uptimeSeconds: 0,
69
+ startedAt: '',
70
+ pid: 0,
71
+ nodeVersion: '',
72
+ platform: '',
73
+ arch: '',
74
+ cpuCount: 0,
75
+ cpuModel: '',
76
+ loadAverage: [],
77
+ runTimes: [],
78
+ sasjsRoot: ''
79
+ },
80
+ memory: {
81
+ rssBytes: 0,
82
+ heapTotalBytes: 0,
83
+ heapUsedBytes: 0,
84
+ externalBytes: 0,
85
+ systemTotalBytes: 0,
86
+ systemFreeBytes: 0
87
+ },
88
+ filesystem: null,
89
+ folders: [],
90
+ logs: {
91
+ folder: '',
92
+ fileCount: 0,
93
+ totalBytes: 0,
94
+ newestFile: null,
95
+ newestModified: null
96
+ }
97
+ }
98
+ }
99
+ },
100
+ 'GET /SASjsApi/admin/logs': {
101
+ implemented: true,
102
+ hostResponses: [401, 500],
103
+ responses: { 200: { files: [] } }
104
+ },
62
105
  'GET /SASjsApi/admin/logs/{fileName}': {
63
- implemented: false,
64
- reason: HOST_OWNED
106
+ implemented: true,
107
+ // 400 and 404 are the name rule's, and this package answers them before the
108
+ // host is asked for anything
109
+ hostResponses: [401, 500],
110
+ responses: {
111
+ 200: {
112
+ fileName: '',
113
+ lines: 0,
114
+ bytesRead: 0,
115
+ truncated: false,
116
+ content: ''
117
+ },
118
+ 400: 'Invalid log file name.',
119
+ 404: 'Log file not found.'
120
+ }
65
121
  },
66
122
  // Auth - the token flow, plus a password change the identity store cannot write
67
123
  'POST /SASjsApi/auth/token': {
@@ -79,11 +135,29 @@ exports.OVERLAY = {
79
135
  // has gone, which a host's store can see and this package cannot.
80
136
  hostResponses: [404]
81
137
  },
82
- // Auth Config - the providers a host was started with, and an LDAP import
83
- 'GET /SASjsApi/authConfig': { implemented: false, reason: HOST_CONFIG },
138
+ // Auth Config - the providers a host was started with, and an LDAP import.
139
+ // Both are administrator routes at the host's mount point, so 401 and the
140
+ // host's own 500 are host-only statuses; the package answers the body, and
141
+ // refuses a secret that a host tries to hand it.
142
+ 'GET /SASjsApi/authConfig': {
143
+ implemented: true,
144
+ hostResponses: [401, 403, 500],
145
+ responses: {
146
+ 200: {
147
+ ldap: {
148
+ LDAP_URL: '',
149
+ LDAP_BIND_DN: '',
150
+ LDAP_USERS_BASE_DN: '',
151
+ LDAP_GROUPS_BASE_DN: '',
152
+ LDAP_BIND_PASSWORD_SET: true
153
+ }
154
+ }
155
+ }
156
+ },
84
157
  'POST /SASjsApi/authConfig/synchroniseWithLDAP': {
85
- implemented: false,
86
- reason: DIRECTORY
158
+ implemented: true,
159
+ hostResponses: [401, 403, 500],
160
+ responses: { 200: { userCount: 0, groupCount: 0 } }
87
161
  },
88
162
  // Client - the OAuth clients the identity store already holds for sign-in
89
163
  'GET /SASjsApi/client': { implemented: true },
@@ -0,0 +1,123 @@
1
+ /** What produced the build, from the host's build stamp. */
2
+ export interface BuildInfo {
3
+ version: string;
4
+ gitHash: string;
5
+ buildDate: string | null;
6
+ }
7
+ export interface ServerDetails {
8
+ mode: string;
9
+ uptimeSeconds: number;
10
+ startedAt: string;
11
+ pid: number;
12
+ nodeVersion: string;
13
+ platform: string;
14
+ arch: string;
15
+ cpuCount: number;
16
+ cpuModel: string;
17
+ loadAverage: number[];
18
+ runTimes: string[];
19
+ sasjsRoot: string;
20
+ }
21
+ export interface MemoryDetails {
22
+ rssBytes: number;
23
+ heapTotalBytes: number;
24
+ heapUsedBytes: number;
25
+ externalBytes: number;
26
+ systemTotalBytes: number;
27
+ systemFreeBytes: number;
28
+ }
29
+ export interface FilesystemUsage {
30
+ path: string;
31
+ totalBytes: number;
32
+ freeBytes: number;
33
+ usedBytes: number;
34
+ usedPercent: number;
35
+ }
36
+ export interface FolderUsage {
37
+ label: string;
38
+ path: string;
39
+ exists: boolean;
40
+ bytes: number;
41
+ files: number;
42
+ truncated: boolean;
43
+ }
44
+ export interface LogFolderSummary {
45
+ folder: string;
46
+ fileCount: number;
47
+ totalBytes: number;
48
+ newestFile: string | null;
49
+ newestModified: string | null;
50
+ }
51
+ export interface DiagnosticsResponse {
52
+ build: BuildInfo;
53
+ server: ServerDetails;
54
+ memory: MemoryDetails;
55
+ /** `null` when the filesystem holding the root cannot be read. */
56
+ filesystem: FilesystemUsage | null;
57
+ folders: FolderUsage[];
58
+ logs: LogFolderSummary;
59
+ }
60
+ export interface LogFileInfo {
61
+ name: string;
62
+ sizeBytes: number;
63
+ modified: string;
64
+ }
65
+ export interface LogTail {
66
+ fileName: string;
67
+ lines: number;
68
+ bytesRead: number;
69
+ truncated: boolean;
70
+ content: string;
71
+ }
72
+ /** The host's own reports. Absent a report, the route answers 501. */
73
+ export interface AdminReports {
74
+ diagnostics(): Promise<DiagnosticsResponse>;
75
+ /** The access logs this host has written, newest first. */
76
+ logs(): Promise<LogFileInfo[]>;
77
+ /** The tail of one log file, or `undefined` when the folder has no such file. */
78
+ logTail(fileName: string, lines: number): Promise<LogTail | undefined>;
79
+ }
80
+ export interface AdminService {
81
+ diagnostics(): Promise<DiagnosticsResponse>;
82
+ logs(): Promise<LogFileInfo[]>;
83
+ logTail(fileName: string, lines?: number): Promise<LogTail>;
84
+ }
85
+ /** The documented defaults on the route's `lines` parameter. */
86
+ export declare const DEFAULT_LOG_LINES = 200;
87
+ export declare const MAX_LOG_LINES = 5000;
88
+ /**
89
+ * The diagnostics body, checked field by field.
90
+ *
91
+ * A host that cannot read its filesystem states `filesystem: null`, which the
92
+ * document allows; a host that cannot read anything at all should refuse the
93
+ * request itself, because an empty object here renders as a page of zeroes.
94
+ */
95
+ export declare const normaliseDiagnostics: (report: DiagnosticsResponse) => DiagnosticsResponse;
96
+ /** The log listing, checked entry by entry. */
97
+ export declare const normaliseLogFiles: (files: LogFileInfo[]) => LogFileInfo[];
98
+ /**
99
+ * A log file name the route will hand to a host.
100
+ *
101
+ * The rule is sasjs/server's, applied before the filesystem: a bare name ending
102
+ * in `.log`. `.` and `..` are refused by the basename check, because both have a
103
+ * basename equal to themselves and neither ends in `.log`.
104
+ */
105
+ export declare const checkLogFileName: (fileName: string) => string;
106
+ /**
107
+ * How many trailing lines to return.
108
+ *
109
+ * A caller's `lines` is text on the wire, so an absent or unusable value is the
110
+ * documented default rather than a refusal - the parameter is a preference, not
111
+ * a requirement. The ceiling is the document's maximum, so a host is never asked
112
+ * to read more than it stated it would.
113
+ */
114
+ export declare const logLines: (lines?: number | string) => number;
115
+ /**
116
+ * The admin service, over the host's reports.
117
+ *
118
+ * The name rule and the line clamp run here, before the host is asked for
119
+ * anything: a host that resolves an unchecked name is a host that can be talked
120
+ * into reading outside its log folder.
121
+ */
122
+ export declare const createAdminService: (reports: AdminReports) => AdminService;
123
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../../src/admin/service.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,201 @@
1
+ /**
2
+ * The three Admin reports: this host's own process, memory, disk and logs.
3
+ *
4
+ * The values are the host's - a pid, a folder walk, the tail of a file - and a
5
+ * browser build has no equivalent, so the reports are supplied through a port.
6
+ * What this file owns is everything a client keys on:
7
+ *
8
+ * - the body's shape, because a diagnostics page that reads
9
+ * `memory.rssBytes` renders `NaN` when a host omits it, and a report that is
10
+ * missing a field is a host bug rather than an empty reading;
11
+ * - the log file name rule: a bare name ending in `.log`, refused with `400`
12
+ * for anything that could resolve outside the log folder (`..`, a
13
+ * separator, an absolute path). The host resolves the name inside its own
14
+ * folder - this is the same rule sasjs/server applies before it touches the
15
+ * filesystem, and doing it here means both hosts refuse a traversal the same
16
+ * way;
17
+ * - `404` for a name that is not there, `200` with a bounded tail otherwise,
18
+ * and the line count clamped to the documented default and maximum so a
19
+ * caller cannot ask a host to read a gigabyte.
20
+ *
21
+ * `GET /admin/diagnostics`, `GET /admin/logs` and `GET /admin/logs/{fileName}`
22
+ * are mounted behind the host's own administrator middleware (sasjs/server puts
23
+ * `authenticateAccessToken` and `verifyAdmin` in front of all three), so the
24
+ * caller's right to read these is the host's decision and is marked
25
+ * `hostResponses` in the overlay.
26
+ */
27
+ import { ApiError } from '../types.js';
28
+ /** The documented defaults on the route's `lines` parameter. */
29
+ export const DEFAULT_LOG_LINES = 200;
30
+ export const MAX_LOG_LINES = 5000;
31
+ const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
32
+ const isNumber = (value) => typeof value === 'number' && Number.isFinite(value);
33
+ const isString = (value) => typeof value === 'string';
34
+ const requireString = (holder, key, where) => {
35
+ if (!isString(holder[key]))
36
+ throw new Error(`The ${where} report states \`${key}\` as ${JSON.stringify(holder[key])}; the document states a string, and a client that renders it would print the value as it stands.`);
37
+ };
38
+ const requireNumber = (holder, key, where) => {
39
+ if (!isNumber(holder[key]))
40
+ throw new Error(`The ${where} report states \`${key}\` as ${JSON.stringify(holder[key])}; the document states a number, and a client that renders it would print NaN.`);
41
+ };
42
+ const requireObject = (holder, key, where) => {
43
+ const value = holder[key];
44
+ if (!isObject(value))
45
+ throw new Error(`The ${where} report states \`${key}\` as ${JSON.stringify(value)}; the document states an object.`);
46
+ return value;
47
+ };
48
+ /**
49
+ * The diagnostics body, checked field by field.
50
+ *
51
+ * A host that cannot read its filesystem states `filesystem: null`, which the
52
+ * document allows; a host that cannot read anything at all should refuse the
53
+ * request itself, because an empty object here renders as a page of zeroes.
54
+ */
55
+ export const normaliseDiagnostics = (report) => {
56
+ if (!isObject(report))
57
+ throw new Error('The diagnostics report is not an object.');
58
+ const build = requireObject(report, 'build', 'diagnostics');
59
+ requireString(build, 'version', 'diagnostics build');
60
+ requireString(build, 'gitHash', 'diagnostics build');
61
+ if (!(build.buildDate === null || isString(build.buildDate)))
62
+ throw new Error(`The diagnostics build states \`buildDate\` as ${JSON.stringify(build.buildDate)}; the document states an ISO timestamp or null.`);
63
+ const server = requireObject(report, 'server', 'diagnostics');
64
+ requireString(server, 'mode', 'diagnostics server');
65
+ requireString(server, 'startedAt', 'diagnostics server');
66
+ requireString(server, 'nodeVersion', 'diagnostics server');
67
+ requireString(server, 'platform', 'diagnostics server');
68
+ requireString(server, 'arch', 'diagnostics server');
69
+ requireString(server, 'cpuModel', 'diagnostics server');
70
+ requireString(server, 'sasjsRoot', 'diagnostics server');
71
+ requireNumber(server, 'uptimeSeconds', 'diagnostics server');
72
+ requireNumber(server, 'pid', 'diagnostics server');
73
+ requireNumber(server, 'cpuCount', 'diagnostics server');
74
+ if (!Array.isArray(server.loadAverage) || !server.loadAverage.every(isNumber))
75
+ throw new Error('The diagnostics server report states `loadAverage` as something other than an array of numbers.');
76
+ if (!Array.isArray(server.runTimes) || !server.runTimes.every(isString))
77
+ throw new Error('The diagnostics server report states `runTimes` as something other than an array of strings.');
78
+ const memory = requireObject(report, 'memory', 'diagnostics');
79
+ for (const key of [
80
+ 'rssBytes',
81
+ 'heapTotalBytes',
82
+ 'heapUsedBytes',
83
+ 'externalBytes',
84
+ 'systemTotalBytes',
85
+ 'systemFreeBytes'
86
+ ])
87
+ requireNumber(memory, key, 'diagnostics memory');
88
+ const filesystem = report.filesystem;
89
+ if (filesystem !== null) {
90
+ if (!isObject(filesystem))
91
+ throw new Error(`The diagnostics report states \`filesystem\` as ${JSON.stringify(filesystem)}; the document states an object or null.`);
92
+ requireString(filesystem, 'path', 'diagnostics filesystem');
93
+ for (const key of ['totalBytes', 'freeBytes', 'usedBytes', 'usedPercent'])
94
+ requireNumber(filesystem, key, 'diagnostics filesystem');
95
+ }
96
+ if (!Array.isArray(report.folders))
97
+ throw new Error('The diagnostics report states `folders` as something other than an array.');
98
+ for (const folder of report.folders) {
99
+ if (!isObject(folder))
100
+ throw new Error('The diagnostics report carries a folder that is not an object.');
101
+ const entry = folder;
102
+ requireString(entry, 'label', 'diagnostics folder');
103
+ requireString(entry, 'path', 'diagnostics folder');
104
+ requireNumber(entry, 'bytes', 'diagnostics folder');
105
+ requireNumber(entry, 'files', 'diagnostics folder');
106
+ if (typeof entry.exists !== 'boolean' ||
107
+ typeof entry.truncated !== 'boolean')
108
+ throw new Error('The diagnostics folder report states `exists` or `truncated` as something other than a boolean.');
109
+ }
110
+ const logs = requireObject(report, 'logs', 'diagnostics');
111
+ requireString(logs, 'folder', 'diagnostics logs');
112
+ requireNumber(logs, 'fileCount', 'diagnostics logs');
113
+ requireNumber(logs, 'totalBytes', 'diagnostics logs');
114
+ for (const key of ['newestFile', 'newestModified'])
115
+ if (!(logs[key] === null || isString(logs[key])))
116
+ throw new Error(`The diagnostics logs summary states \`${key}\` as ${JSON.stringify(logs[key])}; the document states a string or null.`);
117
+ return report;
118
+ };
119
+ /** The log listing, checked entry by entry. */
120
+ export const normaliseLogFiles = (files) => {
121
+ if (!Array.isArray(files))
122
+ throw new Error('The log report is not an array of files.');
123
+ return files.map((file) => {
124
+ if (!isObject(file))
125
+ throw new Error('The log report carries an entry that is not an object.');
126
+ const entry = file;
127
+ requireString(entry, 'name', 'logs');
128
+ requireString(entry, 'modified', 'logs');
129
+ requireNumber(entry, 'sizeBytes', 'logs');
130
+ return file;
131
+ });
132
+ };
133
+ /**
134
+ * A log file name the route will hand to a host.
135
+ *
136
+ * The rule is sasjs/server's, applied before the filesystem: a bare name ending
137
+ * in `.log`. `.` and `..` are refused by the basename check, because both have a
138
+ * basename equal to themselves and neither ends in `.log`.
139
+ */
140
+ export const checkLogFileName = (fileName) => {
141
+ if (!fileName ||
142
+ fileName.includes('/') ||
143
+ fileName.includes('\\') ||
144
+ fileName.split(/[\\/]/).pop() !== fileName ||
145
+ !fileName.toLowerCase().endsWith('.log'))
146
+ throw new ApiError(400, 'Invalid log file name.');
147
+ return fileName;
148
+ };
149
+ /**
150
+ * How many trailing lines to return.
151
+ *
152
+ * A caller's `lines` is text on the wire, so an absent or unusable value is the
153
+ * documented default rather than a refusal - the parameter is a preference, not
154
+ * a requirement. The ceiling is the document's maximum, so a host is never asked
155
+ * to read more than it stated it would.
156
+ */
157
+ export const logLines = (lines) => {
158
+ // `?lines=` is absent in every sense that matters: a caller that sent the
159
+ // parameter with no value asked for the default, not for zero lines
160
+ if (lines === undefined || lines === null || lines === '')
161
+ return DEFAULT_LOG_LINES;
162
+ const wanted = Number(lines);
163
+ if (!Number.isFinite(wanted))
164
+ return DEFAULT_LOG_LINES;
165
+ return Math.min(Math.max(Math.trunc(wanted), 1), MAX_LOG_LINES);
166
+ };
167
+ /** The tail, checked against the shape the document states. */
168
+ const normaliseLogTail = (tail) => {
169
+ if (!isObject(tail))
170
+ throw new Error('The log tail report is not an object.');
171
+ const entry = tail;
172
+ requireString(entry, 'fileName', 'log tail');
173
+ requireString(entry, 'content', 'log tail');
174
+ requireNumber(entry, 'lines', 'log tail');
175
+ requireNumber(entry, 'bytesRead', 'log tail');
176
+ if (typeof entry.truncated !== 'boolean')
177
+ throw new Error('The log tail report states `truncated` as something other than a boolean.');
178
+ return tail;
179
+ };
180
+ /**
181
+ * The admin service, over the host's reports.
182
+ *
183
+ * The name rule and the line clamp run here, before the host is asked for
184
+ * anything: a host that resolves an unchecked name is a host that can be talked
185
+ * into reading outside its log folder.
186
+ */
187
+ export const createAdminService = (reports) => ({
188
+ async diagnostics() {
189
+ return normaliseDiagnostics(await reports.diagnostics());
190
+ },
191
+ async logs() {
192
+ return normaliseLogFiles(await reports.logs());
193
+ },
194
+ async logTail(fileName, lines) {
195
+ const name = checkLogFileName(fileName);
196
+ const tail = await reports.logTail(name, logLines(lines));
197
+ if (tail === undefined)
198
+ throw new ApiError(404, 'Log file not found.');
199
+ return normaliseLogTail(tail);
200
+ }
201
+ });