@xeplr/monitor 0.1.3 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +138 -125
  2. package/api/README.md +71 -0
  3. package/api/app.js +46 -0
  4. package/api/bin/auth.js +37 -0
  5. package/api/bin/www +72 -0
  6. package/api/db/setup.js +10 -0
  7. package/api/env.required.js +37 -0
  8. package/api/lib/host.js +188 -0
  9. package/api/lib/jobs.js +83 -0
  10. package/api/lib/services.js +67 -0
  11. package/api/lib/stats.js +362 -0
  12. package/{lib → api/lib}/systemd.js +75 -14
  13. package/api/migrations/0001_monitor.sql +43 -0
  14. package/api/migrations/0002_backup_connections.sql +26 -0
  15. package/api/migrations/0003_settings_audit.sql +18 -0
  16. package/api/migrations/0004_monitor_stats.sql +73 -0
  17. package/api/migrations/README.md +9 -0
  18. package/api/migrations-auth/0006_monitor.sql +56 -0
  19. package/api/migrations-auth/0007_monitor_home.sql +42 -0
  20. package/api/migrations-auth/0008_backups.sql +44 -0
  21. package/api/migrations-auth/0009_app_settings.sql +44 -0
  22. package/api/migrations-auth/0010_monitor_history.sql +22 -0
  23. package/api/models/index.js +18 -0
  24. package/api/package-lock.json +2839 -0
  25. package/api/package.json +39 -0
  26. package/api/production.env.example +61 -0
  27. package/api/routes/appSettings.js +73 -0
  28. package/api/routes/index.js +47 -0
  29. package/api/routes/monitor.js +196 -0
  30. package/api/setup.schema.js +166 -0
  31. package/deploy/control.sh +27 -0
  32. package/deploy/deploy.js +183 -0
  33. package/deploy/install.sh +193 -77
  34. package/deploy/settings.cjs +93 -0
  35. package/package.json +28 -47
  36. package/ui/.env +8 -0
  37. package/ui/README.md +29 -0
  38. package/ui/index.html +13 -0
  39. package/ui/package-lock.json +2094 -0
  40. package/ui/package.json +31 -0
  41. package/ui/pages.json +33 -0
  42. package/ui/public/logo-wide.svg +17 -0
  43. package/ui/public/logo.svg +10 -0
  44. package/ui/src/App.jsx +130 -0
  45. package/ui/src/api/monitor.js +6 -0
  46. package/ui/src/index.css +414 -0
  47. package/ui/src/main.jsx +27 -0
  48. package/ui/src/pages/Connections.jsx +9 -0
  49. package/ui/src/pages/Home.jsx +8 -0
  50. package/ui/src/pages/Monitor.jsx +9 -0
  51. package/ui/vite.config.js +56 -0
  52. package/bin/deploy.js +0 -181
  53. package/bin/server.js +0 -19
  54. package/bin/users.js +0 -86
  55. package/deploy/monitor.env.example +0 -16
  56. package/deploy/nginx.conf.example +0 -18
  57. package/deploy/sudoers.example +0 -13
  58. package/deploy/xeplr-monitor.service +0 -26
  59. package/index.js +0 -89
  60. package/lib/router.js +0 -179
  61. package/lib/services.js +0 -76
  62. package/lib/session.js +0 -78
  63. package/lib/store.js +0 -73
  64. package/lib/users.js +0 -119
  65. package/public/assets/index-BsBYpvNI.js +0 -18
  66. package/public/assets/index-DNZBwVTn.css +0 -1
  67. package/public/index.html +0 -15
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Mandatory env vars for the xeplr-monitor API process. Checked at startup
3
+ * (bin/www) and at build (`npm run check-env`).
4
+ *
5
+ * SPREAD EACH LIBRARY'S OWN LIST rather than re-typing its variable names.
6
+ * The names belong to the library, so a new requirement it adds lands here on
7
+ * the next upgrade with nothing to remember — and nothing drifts out of step.
8
+ * Only APP-SPECIFIC names are written out literally below.
9
+ */
10
+ module.exports = [
11
+ // ENCRYPTION_KEY, AUTH_JWT_SECRET, AUTH_PORT, AUTH_DB_NAME,
12
+ // XEPLR_AUTH_MIGRATIONS, AUTH_SUPER_ADMIN_EMAIL / _PASSWORD, REDIS_PREFIX,
13
+ // AUTH_TENANT_HEADER, and the sign-up settings: AUTH_REGISTER_ROLES,
14
+ // AUTH_ACTIVATION_URL, AUTH_RESET_URL
15
+ ...require('@xeplr/auth').requiredEnv,
16
+
17
+ // ── this app's own ──
18
+ 'XEPLR_MONITOR_PORT',
19
+
20
+ // Where the sign-in service is. createApp gates every route by default and
21
+ // validates against this, so a missing one already stops the boot with a
22
+ // named variable — listing it here just moves the same complaint to
23
+ // `npm run check-env`, before anything starts at all.
24
+ 'AUTH_URL',
25
+
26
+ // This app's own database. NEVER defaulted: a wrong-but-present name boots
27
+ // clean, migrates, serves traffic and reads as EMPTY DATA rather than as an
28
+ // error — the most expensive way for this to go wrong.
29
+ 'DB_API',
30
+
31
+ 'XEPLR_MONITOR_CONNECTION',
32
+
33
+ // The backup jobs' own database (DB_JOBS), and where a dump is written
34
+ // before it goes to S3 (XEPLR_DATA_DIR, absolute) — lib/jobs.js.
35
+ ...require('@xeplr/jobs').requiredEnv,
36
+ ...require('@xeplr/actions').requiredEnv,
37
+ ];
@@ -0,0 +1,188 @@
1
+ // THE SERVER ITSELF — memory, CPU, disks, uptime — for the Home page. Read
2
+ // from the kernel's own files (/proc, statfs), no command and no sudo, the
3
+ // same numbers `free`, `uptime` and `df` show — and what the cache holds and
4
+ // for whom (cgroup v2's memory.stat, readable without sudo too). Linux only; elsewhere every
5
+ // figure is null and `linux` is false, so the page can say so.
6
+ var fs = require('fs');
7
+ var os = require('os');
8
+
9
+ // The filesystems a person means by "disk": not proc, tmpfs, overlay and the rest.
10
+ var DISK_TYPES = ['ext2', 'ext3', 'ext4', 'xfs', 'btrfs', 'zfs', 'f2fs', 'vfat', 'exfat', 'ntfs', 'ntfs3', 'jfs', 'reiserfs'];
11
+
12
+ function readText(file) { try { return fs.readFileSync(file, 'utf8'); } catch (e) { return null; } }
13
+
14
+ /** /proc/meminfo as bytes by key (its values are kB). */
15
+ function meminfo(text) {
16
+ var out = {};
17
+ String(text || '').split('\n').forEach(function(line) {
18
+ var m = /^(\w+(?:\(\w+\))?):\s+(\d+)(?:\s+kB)?$/.exec(line.trim());
19
+ if (m) out[m[1]] = Number(m[2]) * 1024;
20
+ });
21
+ return out;
22
+ }
23
+
24
+ /**
25
+ * Memory the way `free` counts it: cache is page cache plus reclaimable slab,
26
+ * less shared memory (which `free` counts as used); used is what is left after
27
+ * free, buffers and cache. `available` is the kernel's own estimate of what a
28
+ * new program could have without swapping — the number that says whether the
29
+ * server is short of memory.
30
+ */
31
+ function memoryOf(m) {
32
+ if (!m.MemTotal) return null;
33
+ var cache = (m.Cached || 0) + (m.SReclaimable || 0) - (m.Shmem || 0);
34
+ var used = m.MemTotal - (m.MemFree || 0) - (m.Buffers || 0) - cache;
35
+ return {
36
+ totalBytes: m.MemTotal,
37
+ usedBytes: Math.max(0, used),
38
+ freeBytes: m.MemFree || 0,
39
+ availableBytes: m.MemAvailable === undefined ? null : m.MemAvailable,
40
+ buffersBytes: m.Buffers || 0,
41
+ cacheBytes: Math.max(0, cache),
42
+ sharedBytes: m.Shmem || 0,
43
+ // What the cache & buffers hold: they add up to cacheBytes + buffersBytes.
44
+ cacheKinds: [
45
+ { key: 'files', label: 'File contents', bytes: Math.max(0, (m.Cached || 0) - (m.Shmem || 0)) },
46
+ { key: 'kernel', label: 'Kernel objects', bytes: m.SReclaimable || 0 },
47
+ { key: 'buffers', label: 'Disk buffers', bytes: m.Buffers || 0 }
48
+ ],
49
+ swapTotalBytes: m.SwapTotal || 0,
50
+ swapUsedBytes: Math.max(0, (m.SwapTotal || 0) - (m.SwapFree || 0))
51
+ };
52
+ }
53
+
54
+ var CGROUP_ROOT = '/sys/fs/cgroup';
55
+ var TOP_GROUPS = 12;
56
+
57
+ /** A cgroup's memory.stat as bytes by key. */
58
+ function memoryStat(text) {
59
+ var out = {};
60
+ String(text || '').split('\n').forEach(function(line) {
61
+ var f = line.trim().split(' ');
62
+ if (f.length === 2 && /^\d+$/.test(f[1])) out[f[0]] = Number(f[1]);
63
+ });
64
+ return out;
65
+ }
66
+
67
+ /** What a cgroup holds in cache, counted as free counts it: file pages less shared memory, plus kernel objects it can give back. */
68
+ function cacheOfStat(st) {
69
+ return Math.max(0, (st.file || 0) - (st.shmem || 0)) + (st.slab_reclaimable || 0);
70
+ }
71
+
72
+ function subdirs(dir) {
73
+ try { return fs.readdirSync(dir, { withFileTypes: true }).filter(function(d) { return d.isDirectory(); }).map(function(d) { return d.name; }); } catch (e) { return []; }
74
+ }
75
+
76
+ /**
77
+ * WHO THE CACHE IS FOR — cgroup v2 charges each file page to the group whose
78
+ * process first read it: each service under system.slice (postgresql.service,
79
+ * nginx.service…), and the other top groups whole (user.slice: people signed
80
+ * in; init.scope). Biggest first, the top TOP_GROUPS; the rest of the cache —
81
+ * the kernel's own, or pages whose group is gone — as `others`. null without
82
+ * cgroup v2 (no memory.stat at the root's children).
83
+ * @returns {{ groups: Array<{ name: string, bytes: number }>, othersBytes: number }|null}
84
+ */
85
+ function cacheByGroup(totalCache, root) {
86
+ root = root || CGROUP_ROOT;
87
+ var groups = [];
88
+ subdirs(root).forEach(function(top) {
89
+ var kids = /\.slice$/.test(top) && top !== 'user.slice' ? subdirs(root + '/' + top).filter(function(k) { return readText(root + '/' + top + '/' + k + '/memory.stat') !== null; }) : [];
90
+ (kids.length ? kids.map(function(k) { return top + '/' + k; }) : [top]).forEach(function(path) {
91
+ var text = readText(root + '/' + path + '/memory.stat');
92
+ if (text === null) return;
93
+ var bytes = cacheOfStat(memoryStat(text));
94
+ if (bytes > 0) groups.push({ name: path.split('/').pop(), bytes: bytes });
95
+ });
96
+ });
97
+ if (!groups.length) return null;
98
+ groups.sort(function(a, b) { return b.bytes - a.bytes; });
99
+ var top = groups.slice(0, TOP_GROUPS);
100
+ var shown = top.reduce(function(n, g) { return n + g.bytes; }, 0);
101
+ return { groups: top, othersBytes: Math.max(0, (totalCache || 0) - shown) };
102
+ }
103
+
104
+ // CPU use needs two readings of /proc/stat's first line: the share of the
105
+ // time between them that was not idle.
106
+ var lastCpu = null;
107
+ /** /proc/stat's first line as CPU ticks: { idle, total } (idle counts iowait), or null. */
108
+ function cpuTicks(text) {
109
+ var m = /^cpu\s+(.+)$/m.exec(String(text || ''));
110
+ if (!m) return null;
111
+ var f = m[1].trim().split(/\s+/).map(Number);
112
+ return { idle: f[3] + (f[4] || 0), total: f.reduce(function(a, b) { return a + b; }, 0) };
113
+ }
114
+
115
+ function cpuUse(text, at) {
116
+ var m = /^cpu\s+(.+)$/m.exec(String(text || ''));
117
+ if (!m) return null;
118
+ var f = m[1].trim().split(/\s+/).map(Number);
119
+ var idle = f[3] + (f[4] || 0); // idle + iowait
120
+ var total = f.reduce(function(a, b) { return a + b; }, 0);
121
+ var prev = lastCpu;
122
+ if (prev && at - prev.at < 1000) return prev.percent;
123
+ var percent = prev && total > prev.total ? Math.round((1 - (idle - prev.idle) / (total - prev.total)) * 1000) / 10 : null;
124
+ lastCpu = { idle: idle, total: total, at: at, percent: percent };
125
+ return percent;
126
+ }
127
+
128
+ /** Each real disk once (by device), with its size, what is used and what is left. */
129
+ function disks(mountsText) {
130
+ var seen = new Set();
131
+ var out = [];
132
+ String(mountsText || '').split('\n').forEach(function(line) {
133
+ var f = line.split(' ');
134
+ if (f.length < 3 || DISK_TYPES.indexOf(f[2]) < 0) return;
135
+ var device = f[0];
136
+ var mount = f[1].replace(/\\040/g, ' ');
137
+ if (seen.has(device)) return;
138
+ // A single file mounted from a disk (a container's /etc/resolv.conf) is
139
+ // not a disk of its own: a disk is mounted on a folder.
140
+ try { if (!fs.statSync(mount).isDirectory()) return; } catch (e) { return; }
141
+ seen.add(device);
142
+ var s;
143
+ try { s = fs.statfsSync(mount); } catch (e) { return; }
144
+ var total = s.blocks * s.bsize;
145
+ if (!total) return;
146
+ var free = s.bfree * s.bsize;
147
+ out.push({ device: device, mount: mount, type: f[2], totalBytes: total, usedBytes: total - free, availableBytes: s.bavail * s.bsize });
148
+ });
149
+ return out.sort(function(a, b) { return a.mount.localeCompare(b.mount); });
150
+ }
151
+
152
+ function osName() {
153
+ var m = /^PRETTY_NAME="?([^"\n]*)"?$/m.exec(readText('/etc/os-release') || '');
154
+ return m ? m[1] : os.type();
155
+ }
156
+
157
+ function withCacheByGroup(m) {
158
+ if (m) m.cacheBy = cacheByGroup(m.cacheBytes + m.buffersBytes);
159
+ return m;
160
+ }
161
+
162
+ /** Everything the Home page shows, now. */
163
+ function stats() {
164
+ var linux = process.platform === 'linux' && readText('/proc/meminfo') !== null;
165
+ var uptime = linux ? Number(String(readText('/proc/uptime') || '').split(' ')[0]) : null;
166
+ var cpus = os.cpus();
167
+ return {
168
+ linux: linux,
169
+ at: new Date().toISOString(),
170
+ host: {
171
+ name: os.hostname(),
172
+ os: linux ? osName() : os.type(),
173
+ kernel: os.release(),
174
+ arch: os.arch(),
175
+ uptimeSeconds: uptime === null || isNaN(uptime) ? null : Math.round(uptime)
176
+ },
177
+ memory: linux ? withCacheByGroup(memoryOf(meminfo(readText('/proc/meminfo')))) : null,
178
+ cpu: {
179
+ cores: cpus.length,
180
+ model: cpus[0] ? cpus[0].model.trim() : null,
181
+ load: linux ? os.loadavg().map(function(x) { return Math.round(x * 100) / 100; }) : null,
182
+ usePercent: linux ? cpuUse(readText('/proc/stat'), Date.now()) : null
183
+ },
184
+ disks: linux ? disks(readText('/proc/mounts')) : []
185
+ };
186
+ }
187
+
188
+ module.exports = { stats: stats, meminfo: meminfo, memoryOf: memoryOf, memoryStat: memoryStat, cacheByGroup: cacheByGroup, disks: disks, cpuUse: cpuUse, cpuTicks: cpuTicks, readText: readText, DISK_TYPES: DISK_TYPES };
@@ -0,0 +1,83 @@
1
+ // THE BACKUP JOBS — @xeplr/jobs, in their own database (DB_JOBS), run by this
2
+ // API, with @xeplr/backups' two actions: backup-database (databases on a
3
+ // saved server → S3) and backup-folder (folders of THIS APP'S OWN data folder
4
+ // → S3). Each job is set on the Jobs page (@xeplr/ui-jobs), on its schedule.
5
+ //
6
+ // A job holds the connections' ids; @xeplr/backups' resolveConnection fills
7
+ // in the logins only for the run, so no password is in a job or its history.
8
+ //
9
+ // THE HISTORY BEHIND THE CHARTS is two system jobs of the same runner (no
10
+ // timer of our own): "monitor-sample" every minute (lib/stats.js record():
11
+ // a reading of each service and of the server, and what their logs said)
12
+ // and "monitor-prune" daily (what is older than 30 days goes, and the
13
+ // sampler's own run history older than a day — 1,440 runs a day would
14
+ // otherwise fill the Jobs page). System jobs: on the Jobs page, can be run
15
+ // or paused there, never edited or deleted.
16
+ var path = require('path');
17
+ var jobs = require('@xeplr/jobs');
18
+ var backups = require('@xeplr/backups');
19
+ var stats = require('./stats');
20
+
21
+ var SAMPLE_JOB = 'xeplr-monitor-sample';
22
+ var PRUNE_JOB = 'xeplr-monitor-prune';
23
+ var RUNS_KEPT_MS = 24 * 3600 * 1000;
24
+
25
+ var ACTIONS = [
26
+ {
27
+ name: 'monitor-sample',
28
+ description: 'Record a reading of every watched service and of the server, and count what their logs said since the last run (the charts).',
29
+ inputSchema: [],
30
+ example: { services: 8, lines: 412, failed: [], server: true },
31
+ execute: function(ctx) { return stats.record({ signal: ctx.system && ctx.system.signal }); }
32
+ },
33
+ {
34
+ name: 'monitor-prune',
35
+ description: 'Remove readings, log counts and requests older than ' + stats.KEEP_DAYS + ' days, and the sampler\'s own runs older than a day.',
36
+ inputSchema: [],
37
+ example: { monitor_samples: 11520 },
38
+ execute: async function() {
39
+ var out = await stats.prune();
40
+ var sampler = await jobs.boundModels().Job.unscopedQuery().findById(SAMPLE_JOB);
41
+ out.samplerRuns = sampler ? await jobs.boundModels().JobOccurrence.unscopedQuery()
42
+ .where({ jobId: SAMPLE_JOB }).where('startedAt', '<', new Date(Date.now() - RUNS_KEPT_MS).toISOString()).del() : 0;
43
+ return out;
44
+ }
45
+ }
46
+ ];
47
+
48
+ /** The jobs database: made if missing, then jobs' own migrations; and backups' table in this app's own. */
49
+ async function migrate() {
50
+ var db = require('@xeplr/db');
51
+ var resolved = await db.resolveConfig('api');
52
+ await db.ensureDatabaseFor(resolved, process.env.DB_JOBS);
53
+ var result = await db.migrator.up({
54
+ db: process.env.DB_JOBS,
55
+ dir: path.join(path.dirname(require.resolve('@xeplr/jobs')), 'migrations'),
56
+ connectionName: 'api'
57
+ });
58
+ if (result.migrations.length) console.log('[jobs] ran migrations: ' + result.migrations.join(', '));
59
+ // backup_connections — IF NOT EXISTS: this app made it itself before
60
+ // (migrations/0002), and keeps its rows.
61
+ var own = await db.sqlMigrator.up({ db: process.env.DB_API, dir: backups.migrationsDir, connectionName: 'api' });
62
+ if (own.migrations.length) console.log('[backups] ran migrations: ' + own.migrations.join(', '));
63
+ }
64
+
65
+ /** Migrate, start @xeplr/jobs with only the backup actions, start the scheduler. */
66
+ async function start() {
67
+ await migrate();
68
+ await jobs.init({
69
+ database: process.env.DB_JOBS,
70
+ connection: process.env.XEPLR_MONITOR_CONNECTION,
71
+ defaultActions: false,
72
+ resolveConnection: backups.resolveConnection
73
+ });
74
+ var names = backups.register(jobs);
75
+ ACTIONS.forEach(function(a) { jobs.registerAction(a); names.push(a.name); });
76
+ // Kept by id: starting again brings them up to date, and keeps a pause.
77
+ await jobs.keepSchedule(SAMPLE_JOB, { name: 'Monitor: record a reading', description: 'Every minute: each service and the server, and their logs (the charts).', actionName: 'monitor-sample', inputs: {}, cron: '* * * * *' }, { system: true });
78
+ await jobs.keepSchedule(PRUNE_JOB, { name: 'Monitor: remove old readings', description: 'Daily: what is older than ' + stats.KEEP_DAYS + ' days.', actionName: 'monitor-prune', inputs: {}, cron: '30 3 * * *' }, { system: true });
79
+ jobs.startScheduler({ intervalMs: 10000 });
80
+ console.log('[jobs] scheduler started: ' + names.join(', '));
81
+ }
82
+
83
+ module.exports = { start: start };
@@ -0,0 +1,67 @@
1
+ // THE SERVICES THE MONITOR WATCHES — rows of monitor_services, added by hand.
2
+ // Any systemd service on the server can be added; a service is only ever
3
+ // controlled once it is on this list. Who may add or control one is decided
4
+ // by roles (migrations-auth/0006), not by a pattern.
5
+ var { generateId } = require('@xeplr/utils');
6
+ var systemd = require('./systemd');
7
+ var { MonitoredService, MonitorAudit } = require('../models');
8
+
9
+ function refuse(message, status) { var e = new Error(message); e.status = status || 400; return e; }
10
+
11
+ function all() { return MonitoredService.query().orderBy('label'); }
12
+
13
+ /** One watched service by its unit, or a 404. */
14
+ async function get(unit) {
15
+ var s = await MonitoredService.query().findOne({ unit: unit });
16
+ if (!s) throw refuse('"' + unit + '" is not one of the services the monitor watches', 404);
17
+ return s;
18
+ }
19
+
20
+ /** A unit checked: a proper name, and known to systemd. → its full name. */
21
+ async function checked(name) {
22
+ var unit = systemd.unitName(name);
23
+ var st = await systemd.status(unit);
24
+ if (!st.exists) throw refuse('systemd has no service called ' + unit + ' on this server', 404);
25
+ return unit;
26
+ }
27
+
28
+ /** Watch a service: { unit, label }. */
29
+ async function add(body, by) {
30
+ var unit = await checked(body && body.unit);
31
+ if (await MonitoredService.query().findOne({ unit: unit })) throw refuse(unit + ' is already on the list', 409);
32
+ var label = String((body && body.label) || '').trim().slice(0, 80) || unit.replace(/\.service$/, '');
33
+ return MonitoredService.query().insert({ id: generateId(), unit: unit, label: label, addedBy: by });
34
+ }
35
+
36
+ /** Change a watched service in place: its label, or which unit it is. */
37
+ async function edit(unit, body) {
38
+ var s = await get(unit);
39
+ var patch = {};
40
+ if (body.unit !== undefined && systemd.unitName(body.unit) !== unit) {
41
+ var next = await checked(body.unit);
42
+ if (await MonitoredService.query().findOne({ unit: next })) throw refuse(next + ' is already on the list', 409);
43
+ patch.unit = next;
44
+ }
45
+ if (body.label !== undefined) patch.label = String(body.label).trim().slice(0, 80) || (patch.unit || unit).replace(/\.service$/, '');
46
+ return Object.keys(patch).length ? MonitoredService.query().patchAndFetchById(s.id, patch) : s;
47
+ }
48
+
49
+ /** Stop watching a service. The service itself is not touched. */
50
+ async function remove(unit) {
51
+ var s = await get(unit);
52
+ await MonitoredService.query().deleteById(s.id);
53
+ }
54
+
55
+ /** One line of the audit log. Never throws: a failed write must not turn a done action into an error. */
56
+ async function audit(entry) {
57
+ try {
58
+ await MonitorAudit.query().insert({ id: generateId(), email: entry.email || null, ip: entry.ip || null, action: entry.action, unit: entry.unit || null, ok: Boolean(entry.ok), error: entry.error || null });
59
+ } catch (e) { console.error('[monitor] audit not written:', e.message); }
60
+ }
61
+
62
+ async function recentAudit(limit) {
63
+ var rows = await MonitorAudit.query().orderBy('recordCreatedDate', 'desc').limit(Math.min(Math.max(parseInt(limit, 10) || 300, 1), 1000));
64
+ return rows.map(function(r) { return { at: new Date(r.recordCreatedDate).toISOString(), email: r.email, ip: r.ip, action: r.action, unit: r.unit, ok: r.ok, error: r.error }; });
65
+ }
66
+
67
+ module.exports = { all: all, get: get, add: add, edit: edit, remove: remove, audit: audit, recentAudit: recentAudit };