@deveye/types 0.24.5 → 0.25.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.
@@ -142,6 +142,8 @@ export interface RecordedCalls {
142
142
  livePublishes: { workspaceId: number; event: string; payload: unknown }[];
143
143
  /** Accounts beaten through `live.accountChanged`, in order. */
144
144
  accountChanges: number[];
145
+ /** How many times `live.pendingChanged` was called. */
146
+ pendingChanges: number;
145
147
  }
146
148
 
147
149
  /** What a command's test context records on top of {@link RecordedCalls}. */
@@ -220,6 +222,7 @@ function recordingDevices(
220
222
  )
221
223
  )
222
224
  : Promise.resolve(devices.find((d) => d.id === id) ?? testDevice({ id })),
225
+ assertControl: () => Promise.resolve(),
223
226
  list: () => Promise.resolve([...devices]),
224
227
  isOnline: (id) => devices.find((d) => d.id === id)?.online ?? true
225
228
  };
@@ -541,6 +544,7 @@ export function createTestContext<Repo = undefined>(
541
544
  pinnedInstants: [],
542
545
  livePublishes: [],
543
546
  accountChanges: [],
547
+ pendingChanges: 0,
544
548
  progress: []
545
549
  };
546
550
  const isOwner = overrides.isOwner ?? true;
@@ -573,6 +577,7 @@ export function createTestContext<Repo = undefined>(
573
577
  email: `user${overrides.userId ?? 1}@deveye.test`,
574
578
  username: `user${overrides.userId ?? 1}`,
575
579
  isAdmin: overrides.isAdmin ?? false,
580
+ canModerate: overrides.isAdmin ?? false,
576
581
  e2e: false,
577
582
  suspended: false,
578
583
  created: 0
@@ -616,7 +621,19 @@ export function createTestContext<Repo = undefined>(
616
621
  ticket: (payload) =>
617
622
  Promise.resolve(
618
623
  `ticket:${JSON.stringify({ userId: overrides.userId ?? 1, workspaceId, payload, unlocked: overrides.unlocked ?? true })}`
619
- )
624
+ ),
625
+ // Only a ticket this caller minted, in this workspace, reads back.
626
+ redeem: (ticket) => {
627
+ if (!ticket.startsWith('ticket:')) return Promise.resolve(null);
628
+ const parsed = JSON.parse(ticket.slice('ticket:'.length)) as {
629
+ userId: number;
630
+ workspaceId: number;
631
+ payload: unknown;
632
+ };
633
+ const mine =
634
+ parsed.userId === (overrides.userId ?? 1) && parsed.workspaceId === workspaceId;
635
+ return Promise.resolve(mine ? { payload: parsed.payload } : null);
636
+ }
620
637
  },
621
638
  keys: {
622
639
  sealBytes: (plain) => `sealed:${Buffer.from(plain).toString('base64')}`,
@@ -629,6 +646,9 @@ export function createTestContext<Repo = undefined>(
629
646
  },
630
647
  accountChanged(userId) {
631
648
  recorded.accountChanges.push(userId);
649
+ },
650
+ pendingChanged() {
651
+ recorded.pendingChanges++;
632
652
  }
633
653
  },
634
654
  quota: {
@@ -658,19 +678,19 @@ export function createTestContext<Repo = undefined>(
658
678
  },
659
679
  items: {
660
680
  restrictions: () => Promise.resolve(restrictions),
661
- // The exact rule of the app's dispatcher: the feature first (a
662
- // restriction can only lower), then the row.
681
+ // The app's rule: the item's override replaces the feature level,
682
+ // in both directions; without one, the feature level decides.
663
683
  assert(itemId, level = 'read') {
664
- if (level === 'write' && !canWrite) {
665
- return Promise.reject(new FeatureError('forbidden', 'write required'));
666
- }
667
684
  const restriction = restrictions.get(itemId);
668
685
  if (restriction === 'none') {
669
686
  return Promise.reject(new FeatureError('forbidden', 'item hidden'));
670
687
  }
671
- if (restriction === 'read' && level === 'write') {
688
+ if (level === 'write' && restriction === 'read') {
672
689
  return Promise.reject(new FeatureError('forbidden', 'item read-only'));
673
690
  }
691
+ if (level === 'write' && restriction === undefined && !canWrite) {
692
+ return Promise.reject(new FeatureError('forbidden', 'write required'));
693
+ }
674
694
  return Promise.resolve();
675
695
  },
676
696
  canExtra(itemId, key) {
@@ -756,7 +776,7 @@ export interface RecordedServiceCalls extends RecordedCalls {
756
776
  liveChanges: number[];
757
777
  /** `live.changed` calls that named topics, as `{ workspaceId, topics }` (a bare beat is not listed here). */
758
778
  liveTopicChanges: { workspaceId: number; topics: readonly string[] }[];
759
- /** Emails `accountMail.send` and `sendToAdmins` accepted, with the address they went to. */
779
+ /** Emails `accountMail.send` and `sendToModerators` accepted, with the address they went to. */
760
780
  mails: { userId: number; to: string; message: SdkAccountMailMessage }[];
761
781
  }
762
782
 
@@ -810,6 +830,8 @@ export interface TestServiceOverrides<Repo> {
810
830
  origins?: SdkOrigins;
811
831
  /** Instants `telemetry.snapshot` answers (matched within a second). Default none. */
812
832
  snapshots?: readonly SdkTelemetrySnapshot[];
833
+ /** What `geo.country` answers, by client address. Default none: every address is unknown. */
834
+ countries?: Readonly<Record<string, string>>;
813
835
  /** The feature's domains, every workspace mixed. Default none. */
814
836
  domains?: readonly SdkDomain[];
815
837
  /** The named contracts the host holds (`deps.providers.get(key)`). */
@@ -833,6 +855,7 @@ export function createTestServiceDeps<Repo = undefined>(
833
855
  pinnedInstants: [],
834
856
  livePublishes: [],
835
857
  accountChanges: [],
858
+ pendingChanges: 0,
836
859
  tickers: [],
837
860
  liveChanges: [],
838
861
  liveTopicChanges: [],
@@ -899,6 +922,10 @@ export function createTestServiceDeps<Repo = undefined>(
899
922
  isOnline: devices.isOnline
900
923
  },
901
924
  telemetry: recordingTelemetry(recorded, overrides.snapshots ?? []),
925
+ geo: {
926
+ country: (ip) => overrides.countries?.[ip] ?? null,
927
+ attribution: { text: 'IP Geolocation by DB-IP', url: 'https://db-ip.com' }
928
+ },
902
929
  live: {
903
930
  changed(workspaceId, topics) {
904
931
  recorded.liveChanges.push(workspaceId);
@@ -909,6 +936,9 @@ export function createTestServiceDeps<Repo = undefined>(
909
936
  },
910
937
  accountChanged(userId) {
911
938
  recorded.accountChanges.push(userId);
939
+ },
940
+ pendingChanged() {
941
+ recorded.pendingChanges++;
912
942
  }
913
943
  },
914
944
  quotaFor: () => ({
@@ -989,13 +1019,17 @@ export function createTestServiceDeps<Repo = undefined>(
989
1019
  recorded.mails.push({ userId, to, message });
990
1020
  return Promise.resolve(to);
991
1021
  },
992
- sendToAdmins(message) {
1022
+ sendToModerators(message) {
993
1023
  if (overrides.mailConfigured === false) {
994
1024
  return Promise.reject(new FeatureError('conflict', 'no mail transport'));
995
1025
  }
996
- const admins = (overrides.accounts ?? []).filter((a) => a.isAdmin && !a.suspended);
997
- for (const a of admins) recorded.mails.push({ userId: a.id, to: a.email, message });
998
- return Promise.resolve(admins.map((a) => a.email));
1026
+ const moderators = (overrides.accounts ?? []).filter(
1027
+ (a) => a.canModerate && !a.suspended
1028
+ );
1029
+ for (const a of moderators) {
1030
+ recorded.mails.push({ userId: a.id, to: a.email, message });
1031
+ }
1032
+ return Promise.resolve(moderators.map((a) => a.email));
999
1033
  }
1000
1034
  },
1001
1035
  audit: (entry) => {
@@ -0,0 +1,74 @@
1
+ import assert from 'node:assert/strict';
2
+ import { describe, it } from 'node:test';
3
+
4
+ import {
5
+ looksLikeBot,
6
+ normalizeReferrer,
7
+ originHost,
8
+ parseUserAgent,
9
+ visitorRef
10
+ } from './visitors';
11
+
12
+ describe('originHost and normalizeReferrer', () => {
13
+ it('give the bare host whatever the form, and silence internal navigation', () => {
14
+ assert.equal(originHost('https://Example.com/'), 'example.com');
15
+ assert.equal(originHost('example.com:443/path?q#a'), 'example.com');
16
+ // An IPv6 literal keeps its colons: the port is not split from it.
17
+ assert.equal(originHost('[::1]:3000'), '[::1]:3000');
18
+ assert.equal(
19
+ normalizeReferrer('https://google.com/search?q=x', ['example.com'], 200),
20
+ 'google.com'
21
+ );
22
+ assert.equal(normalizeReferrer('https://example.com/page', ['example.com'], 200), null);
23
+ assert.equal(normalizeReferrer(undefined, [], 200), null);
24
+ assert.equal(normalizeReferrer('https://abcdefghij.com', [], 5), 'abcde');
25
+ });
26
+ });
27
+
28
+ describe('visitorRef', () => {
29
+ it('is stable for the same inputs and changes with any of them', () => {
30
+ const ref = visitorRef('salt', 'scope-a', '203.0.113.7', 'UA');
31
+ assert.equal(ref, visitorRef('salt', 'scope-a', '203.0.113.7', 'UA'));
32
+ assert.equal(ref.length, 16);
33
+ assert.notEqual(ref, visitorRef('other', 'scope-a', '203.0.113.7', 'UA'));
34
+ assert.notEqual(ref, visitorRef('salt', 'scope-b', '203.0.113.7', 'UA'));
35
+ assert.notEqual(ref, visitorRef('salt', 'scope-a', '203.0.113.8', 'UA'));
36
+ assert.notEqual(ref, visitorRef('salt', 'scope-a', '203.0.113.7', 'UB'));
37
+ });
38
+ });
39
+
40
+ describe('parseUserAgent and looksLikeBot', () => {
41
+ it('go from the most specific to the most general', () => {
42
+ const edge =
43
+ 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 Chrome/126.0 Safari/537.36 Edg/126.0';
44
+ const androidTablet =
45
+ 'Mozilla/5.0 (Linux; Android 14; SM-X910) AppleWebKit/537.36 Chrome/126.0 Safari/537.36';
46
+ const iphone =
47
+ 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1';
48
+ assert.deepEqual(parseUserAgent(edge), {
49
+ browser: 'Edge',
50
+ os: 'Windows',
51
+ device: 'desktop'
52
+ });
53
+ assert.deepEqual(parseUserAgent(androidTablet), {
54
+ browser: 'Chrome',
55
+ os: 'Android',
56
+ device: 'tablet'
57
+ });
58
+ assert.deepEqual(parseUserAgent(iphone), {
59
+ browser: 'Safari',
60
+ os: 'iOS',
61
+ device: 'mobile'
62
+ });
63
+ assert.deepEqual(parseUserAgent(''), { browser: null, os: null, device: 'desktop' });
64
+ assert.deepEqual(parseUserAgent('SomethingElse/1.0'), {
65
+ browser: null,
66
+ os: null,
67
+ device: 'desktop'
68
+ });
69
+ assert.equal(looksLikeBot('Mozilla/5.0 (compatible; Googlebot/2.1)'), true);
70
+ assert.equal(looksLikeBot('Slackbot-LinkExpanding 1.0'), true);
71
+ assert.equal(looksLikeBot(edge), false);
72
+ assert.equal(looksLikeBot(undefined), false);
73
+ });
74
+ });
@@ -0,0 +1,146 @@
1
+ /**
2
+ * What a public route may learn about a visitor without keeping anything that
3
+ * identifies them: the kind of browser, whether it is a robot, where it came
4
+ * from, and a daily fingerprint that counts people without recognising them.
5
+ *
6
+ * Pure: no database, no network, no clock. These rules decide whether two
7
+ * visits count as one person, and a mistake here shows as wrong figures, never
8
+ * as an outage.
9
+ */
10
+ import { createHash } from 'node:crypto';
11
+
12
+ /** Browser, system and kind of device, and nothing more: the rest only slices an audience into useless pieces. */
13
+ export interface UserAgentInfo {
14
+ /** `null` when unrecognised: name it in your own words (`'Other'`). */
15
+ browser: string | null;
16
+ /** `null` when unrecognised. */
17
+ os: string | null;
18
+ /** Three values, not a taxonomy. */
19
+ device: 'desktop' | 'mobile' | 'tablet';
20
+ }
21
+
22
+ // The order of the tests is the point: these strings lie by inheritance (Edge
23
+ // says "Chrome", Chrome says "Safari"). From the most specific to the most
24
+ // general; reordering breaks detection without breaking a type.
25
+ function detectBrowser(ua: string): string | null {
26
+ if (/\bEdg[A-Z]?\//.test(ua)) return 'Edge';
27
+ if (/\bOPR\/|\bOpera\b/.test(ua)) return 'Opera';
28
+ if (/\bSamsungBrowser\//.test(ua)) return 'Samsung Internet';
29
+ if (/\bVivaldi\//.test(ua)) return 'Vivaldi';
30
+ if (/\bBrave\//.test(ua)) return 'Brave';
31
+ if (/\bChrome\/|\bCriOS\//.test(ua)) return 'Chrome';
32
+ if (/\bFirefox\/|\bFxiOS\//.test(ua)) return 'Firefox';
33
+ if (/\bSafari\//.test(ua)) return 'Safari';
34
+ return null;
35
+ }
36
+
37
+ function detectOs(ua: string): string | null {
38
+ // Android before Linux: every Android is a Linux and says so.
39
+ if (/\bAndroid\b/.test(ua)) return 'Android';
40
+ // iPadOS 13+ claims to be a Macintosh; `detectDevice` catches it.
41
+ if (/\biPhone\b|\biPad\b|\biPod\b/.test(ua)) return 'iOS';
42
+ if (/\bWindows NT\b/.test(ua)) return 'Windows';
43
+ if (/\bMac OS X\b|\bMacintosh\b/.test(ua)) return 'macOS';
44
+ if (/\bCrOS\b/.test(ua)) return 'ChromeOS';
45
+ if (/\bLinux\b|\bX11\b/.test(ua)) return 'Linux';
46
+ return null;
47
+ }
48
+
49
+ function detectDevice(ua: string): UserAgentInfo['device'] {
50
+ if (/\biPad\b/.test(ua)) return 'tablet';
51
+ // An Android without "Mobile" is a tablet: Google's convention, and the
52
+ // only distinction the string carries.
53
+ if (/\bAndroid\b/.test(ua) && !/\bMobile\b/.test(ua)) return 'tablet';
54
+ if (/\bTablet\b/i.test(ua)) return 'tablet';
55
+ if (/\bMobi\b|\bMobile\b|\biPhone\b|\biPod\b/.test(ua)) return 'mobile';
56
+ return 'desktop';
57
+ }
58
+
59
+ /** An empty string reads as unknown everywhere, which is the truth, not an error. */
60
+ export function parseUserAgent(raw: string | undefined): UserAgentInfo {
61
+ const ua = (raw ?? '').trim();
62
+ if (!ua) return { browser: null, os: null, device: 'desktop' };
63
+ return { browser: detectBrowser(ua), os: detectOs(ua), device: detectDevice(ua) };
64
+ }
65
+
66
+ /**
67
+ * Known robots, kept out of the figures: a search engine passing six times a
68
+ * day doubles the numbers of a quiet page. Deliberately coarse, it only
69
+ * catches what announces itself; the one defence against disguised ones would
70
+ * be a browser fingerprint, which counting without consent rules out.
71
+ */
72
+ const BOT_PATTERN = new RegExp(
73
+ [
74
+ 'bot\\b',
75
+ 'crawler',
76
+ 'spider',
77
+ 'slurp',
78
+ 'facebookexternalhit',
79
+ 'preview',
80
+ 'monitor',
81
+ 'curl/',
82
+ 'wget/',
83
+ 'python-',
84
+ 'headless'
85
+ ].join('|'),
86
+ 'i'
87
+ );
88
+
89
+ export function looksLikeBot(raw: string | undefined): boolean {
90
+ if (!raw) return false;
91
+ return BOT_PATTERN.test(raw);
92
+ }
93
+
94
+ /**
95
+ * The host of an origin, whatever form it came in: `https://example.com`,
96
+ * `example.com:443` and `EXAMPLE.COM/` all read `example.com`. One canonical
97
+ * form on both sides of a comparison (a setting typed by a member, an `Origin`
98
+ * header). The port goes, except in an IPv6 literal where colons are the
99
+ * address itself. Unlike `normaliseDomainHost`, any URL is accepted.
100
+ */
101
+ export function originHost(raw: string): string {
102
+ let value = raw.trim().toLowerCase();
103
+ if (!value) return '';
104
+ value = value.replace(/^[a-z]+:\/\//, '');
105
+ value = value.split('/')[0].split('?')[0].split('#')[0];
106
+ if (!value.startsWith('[')) value = value.split(':')[0];
107
+ return value;
108
+ }
109
+
110
+ /**
111
+ * Where the visitor came from: the host alone, never the full URL, which would
112
+ * quietly collect personal addresses. A visit from one of `ownHosts` gives no
113
+ * referrer, or the first of any ranking would always be the site itself.
114
+ */
115
+ export function normalizeReferrer(
116
+ raw: string | undefined,
117
+ ownHosts: readonly string[],
118
+ maxLength: number
119
+ ): string | null {
120
+ if (!raw) return null;
121
+ const host = originHost(raw);
122
+ if (!host) return null;
123
+ if (ownHosts.includes(host)) return null;
124
+ return host.slice(0, maxLength);
125
+ }
126
+
127
+ /**
128
+ * A visitor's fingerprint: `salt + scope + ip + user agent`, truncated. Neither
129
+ * the address nor the user agent is kept; they go in here and never come out.
130
+ * With a salt that changes every day, the same person cannot be recognised
131
+ * from one day to the next: the price of counting without consent. `scope`
132
+ * (a site key, a link id) keeps one person from carrying the same fingerprint
133
+ * on two of them, so they cannot be crossed.
134
+ */
135
+ export function visitorRef(salt: string, scope: string, ip: string, userAgent: string): string {
136
+ return createHash('sha256')
137
+ .update(salt)
138
+ .update(' ')
139
+ .update(scope)
140
+ .update(' ')
141
+ .update(ip)
142
+ .update(' ')
143
+ .update(userAgent)
144
+ .digest('hex')
145
+ .slice(0, 16);
146
+ }