@deveye/types 0.24.4 → 0.24.6
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.
- package/package.json +1 -1
- package/src/domain/featureRegistry.ts +14 -0
- package/src/domain/home.ts +2 -1
- package/src/domain/live.ts +1 -0
- package/src/domain/notifications.ts +2 -1
- package/src/domain/user.ts +5 -2
- package/src/domain/workspaceRole.ts +6 -1
- package/src/sdk/manifest.ts +6 -1
- package/src/sdk/providers.ts +53 -0
- package/src/sdk/server.ts +86 -3
- package/src/sdk/testing.ts +6 -0
- package/src/sdk/visitors.test.ts +74 -0
- package/src/sdk/visitors.ts +146 -0
package/package.json
CHANGED
|
@@ -348,6 +348,20 @@ export const FEATURE_REGISTRY: readonly (FeatureDescriptor & { id: WorkspaceFeat
|
|
|
348
348
|
hasItems: true,
|
|
349
349
|
itemNoun: 'client',
|
|
350
350
|
shareTier: 'never'
|
|
351
|
+
},
|
|
352
|
+
{
|
|
353
|
+
id: 'shortlinks',
|
|
354
|
+
label: 'Liens courts',
|
|
355
|
+
description:
|
|
356
|
+
'Lecture : les liens et leurs statistiques. Écriture : créer un lien, changer sa destination et ses réglages, le supprimer.',
|
|
357
|
+
icon: 'shortlinks',
|
|
358
|
+
notifies: true,
|
|
359
|
+
notifications: {
|
|
360
|
+
hint: 'Envoyées quand la destination d’un lien ne répond plus, quand elle répond de nouveau, et quand les visites du mois approchent ou atteignent la limite de votre offre.'
|
|
361
|
+
},
|
|
362
|
+
hasItems: true,
|
|
363
|
+
itemNoun: 'lien',
|
|
364
|
+
shareTier: 'open'
|
|
351
365
|
}
|
|
352
366
|
];
|
|
353
367
|
|
package/src/domain/home.ts
CHANGED
package/src/domain/live.ts
CHANGED
package/src/domain/user.ts
CHANGED
|
@@ -58,8 +58,8 @@ export const minimalUserSchema = z.object({
|
|
|
58
58
|
username: z.string().min(1),
|
|
59
59
|
avatar: z.string(),
|
|
60
60
|
color: userColorSchema,
|
|
61
|
-
/**
|
|
62
|
-
|
|
61
|
+
/** Seconds. The last time the account opened or used the app, to within a few minutes; `0` if it never came. */
|
|
62
|
+
lastSeen: z.number().int().nonnegative(),
|
|
63
63
|
created: z.number().int().nonnegative()
|
|
64
64
|
});
|
|
65
65
|
|
|
@@ -154,7 +154,10 @@ export interface UserRow {
|
|
|
154
154
|
/** Espace favori chargé en premier ; `null` → l'espace personnel. */
|
|
155
155
|
default_workspace_id: number | null;
|
|
156
156
|
re_auth_interval: number | null;
|
|
157
|
+
/** Seconds. The last password sign-in; a session renews without one for weeks. */
|
|
157
158
|
last_login: number;
|
|
159
|
+
/** Seconds. The last time the account opened or used the app, to within a few minutes. */
|
|
160
|
+
last_seen: number;
|
|
158
161
|
created: number;
|
|
159
162
|
/** Seconds. When the terms of use were accepted at sign-up; `null` for an account created without a site. */
|
|
160
163
|
terms_accepted_at: number | null;
|
|
@@ -108,7 +108,12 @@ export const workspaceFeatureIdSchema = z.enum([
|
|
|
108
108
|
* brouillon, enregistrer un règlement. Émettre un document et changer
|
|
109
109
|
* l'identité de l'émetteur sont des permissions propres du module.
|
|
110
110
|
*/
|
|
111
|
-
'invoicing'
|
|
111
|
+
'invoicing',
|
|
112
|
+
/**
|
|
113
|
+
* Liens courts. `read` = voir les liens et leurs statistiques, `write` =
|
|
114
|
+
* créer un lien, changer sa destination et ses réglages, le supprimer.
|
|
115
|
+
*/
|
|
116
|
+
'shortlinks'
|
|
112
117
|
]);
|
|
113
118
|
|
|
114
119
|
export type WorkspaceFeatureId = z.infer<typeof workspaceFeatureIdSchema>;
|
package/src/sdk/manifest.ts
CHANGED
|
@@ -168,7 +168,12 @@ export type NativeCapability =
|
|
|
168
168
|
* behalf of its members, on the server's disk or on the S3 bucket the host
|
|
169
169
|
* configured. Declared, because what lands there is billed to the host.
|
|
170
170
|
*/
|
|
171
|
-
| 'objects'
|
|
171
|
+
| 'objects'
|
|
172
|
+
/**
|
|
173
|
+
* The country of a client address (`deps.geo`), from a database the host
|
|
174
|
+
* downloads and refreshes only while an installed module declares this.
|
|
175
|
+
*/
|
|
176
|
+
| 'geoip';
|
|
172
177
|
|
|
173
178
|
/**
|
|
174
179
|
* Settings tabs the shell can render for you.
|
package/src/sdk/providers.ts
CHANGED
|
@@ -454,6 +454,17 @@ export interface GitItemsProvider {
|
|
|
454
454
|
* service, right before the clone, and never store what it returns.
|
|
455
455
|
*/
|
|
456
456
|
openCheckout(repoId: number, workspaceId: number): Promise<GitCheckout | null>;
|
|
457
|
+
/** The repositories at home in the workspace, named `owner/repo`: what a picker offers. */
|
|
458
|
+
list(workspaceId: number): Promise<readonly ItemCandidate[]>;
|
|
459
|
+
/** May this member read the repository? The rule of the feature's screens, the item's override included. */
|
|
460
|
+
authorize(repoId: number, workspaceId: number, userId: number): Promise<SdkAccessVerdict>;
|
|
461
|
+
/**
|
|
462
|
+
* What put the repository's code online since `since`, asked of the forge
|
|
463
|
+
* on the spot: a successful workflow run on the default branch, or a
|
|
464
|
+
* successful deployment outside transient environments. A token without
|
|
465
|
+
* the right to read them answers through `error`, never by throwing.
|
|
466
|
+
*/
|
|
467
|
+
activity(repoId: number, workspaceId: number, since: number): Promise<DeployActivity>;
|
|
457
468
|
}
|
|
458
469
|
|
|
459
470
|
/**
|
|
@@ -534,6 +545,38 @@ export interface DeployItemsProvider {
|
|
|
534
545
|
* an id.
|
|
535
546
|
*/
|
|
536
547
|
labelOf(targetId: number, workspaceId: number): Promise<string | null>;
|
|
548
|
+
/** The targets at home in the workspace: what a picker offers. */
|
|
549
|
+
list(workspaceId: number): Promise<readonly ItemCandidate[]>;
|
|
550
|
+
/** May this member read the target? The rule of the feature's screens, the item's override included. */
|
|
551
|
+
authorize(targetId: number, workspaceId: number, userId: number): Promise<SdkAccessVerdict>;
|
|
552
|
+
/**
|
|
553
|
+
* The target's deployments since `since`, wherever they were started from
|
|
554
|
+
* (DevEye, the provider's own screen, a CI). The target is synced with its
|
|
555
|
+
* provider first, so a deployment that just ended is not missed.
|
|
556
|
+
*/
|
|
557
|
+
activity(targetId: number, workspaceId: number, since: number): Promise<DeployActivity>;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/** An item of another feature, as a picker lists it. */
|
|
561
|
+
export interface ItemCandidate {
|
|
562
|
+
id: number;
|
|
563
|
+
name: string;
|
|
564
|
+
/** What tells two items apart beyond their name (a provider, a host), `null` when nothing does. */
|
|
565
|
+
detail: string | null;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* What an item says of its deployments since a moment (epoch seconds): the
|
|
570
|
+
* latest one that succeeded, one still under way, or why it could not tell.
|
|
571
|
+
* What Uptime asks the sources of a site whose files changed.
|
|
572
|
+
*/
|
|
573
|
+
export interface DeployActivity {
|
|
574
|
+
/** The most recent success that ended at or after `since`; `what` names it for a journal, article included (`le déploiement « api »`). */
|
|
575
|
+
succeeded: { at: number; what: string } | null;
|
|
576
|
+
/** A deployment still queued or running. */
|
|
577
|
+
inFlight: { what: string } | null;
|
|
578
|
+
/** Why the item could not answer in full (a token without the right, a forge down), `null` when it did. */
|
|
579
|
+
error: string | null;
|
|
537
580
|
}
|
|
538
581
|
|
|
539
582
|
/**
|
|
@@ -691,6 +734,16 @@ export interface ProjectsUsageProvider {
|
|
|
691
734
|
workspaceId: number,
|
|
692
735
|
version: string
|
|
693
736
|
): Promise<void>;
|
|
737
|
+
/** May this member read the project? Open tier only: a guarded project is refused as `hidden`. */
|
|
738
|
+
authorize(projectId: number, workspaceId: number, userId: number): Promise<SdkAccessVerdict>;
|
|
739
|
+
/**
|
|
740
|
+
* The Deploy targets and Git repositories one project of the workspace
|
|
741
|
+
* links, by id. Empty for an unknown, projected or guarded project.
|
|
742
|
+
*/
|
|
743
|
+
linkedItems(
|
|
744
|
+
projectId: number,
|
|
745
|
+
workspaceId: number
|
|
746
|
+
): Promise<{ deploy: number[]; git: number[] }>;
|
|
694
747
|
}
|
|
695
748
|
|
|
696
749
|
/**
|
package/src/sdk/server.ts
CHANGED
|
@@ -81,6 +81,14 @@ export {
|
|
|
81
81
|
normaliseDomainHost,
|
|
82
82
|
type SdkDnsRecord
|
|
83
83
|
} from './domains';
|
|
84
|
+
export {
|
|
85
|
+
looksLikeBot,
|
|
86
|
+
normalizeReferrer,
|
|
87
|
+
originHost,
|
|
88
|
+
parseUserAgent,
|
|
89
|
+
visitorRef,
|
|
90
|
+
type UserAgentInfo
|
|
91
|
+
} from './visitors';
|
|
84
92
|
|
|
85
93
|
/**
|
|
86
94
|
* Server-side SDK surface: what a feature module's handlers and background
|
|
@@ -263,6 +271,24 @@ export interface SdkTelemetrySnapshot {
|
|
|
263
271
|
activeConnections: number | null;
|
|
264
272
|
}
|
|
265
273
|
|
|
274
|
+
/**
|
|
275
|
+
* The country of a client address, from a database the host downloads and
|
|
276
|
+
* refreshes on its own (capability `'geoip'`). Answers from memory: cheap
|
|
277
|
+
* enough for a public route. Keep the country, never the address.
|
|
278
|
+
*/
|
|
279
|
+
export interface SdkGeo {
|
|
280
|
+
/**
|
|
281
|
+
* The ISO 3166-1 alpha-2 code (`FR`), or `null` for a private or unknown
|
|
282
|
+
* address, and while the database is not loaded yet.
|
|
283
|
+
*/
|
|
284
|
+
country(ip: string): string | null;
|
|
285
|
+
/**
|
|
286
|
+
* The credit the database's licence requires next to whatever shows its
|
|
287
|
+
* results, with its link: show both wherever a country appears.
|
|
288
|
+
*/
|
|
289
|
+
readonly attribution: { text: string; url: string };
|
|
290
|
+
}
|
|
291
|
+
|
|
266
292
|
/**
|
|
267
293
|
* Read access to the devices' telemetry (capability `'telemetry.read'`,
|
|
268
294
|
* reserved to native-id modules: the metric store is app infrastructure).
|
|
@@ -1302,6 +1328,8 @@ export interface SdkPublicRequest {
|
|
|
1302
1328
|
*/
|
|
1303
1329
|
host?: string;
|
|
1304
1330
|
ip: string;
|
|
1331
|
+
/** The HTTP method as received: a GET route also answers HEAD, which wants no page and counts no visit. */
|
|
1332
|
+
method?: string;
|
|
1305
1333
|
}
|
|
1306
1334
|
|
|
1307
1335
|
/** The reply of a public route, the minimal chainable surface the host maps onto its HTTP server. */
|
|
@@ -1311,6 +1339,16 @@ export interface SdkPublicReply {
|
|
|
1311
1339
|
send(payload?: unknown): unknown;
|
|
1312
1340
|
}
|
|
1313
1341
|
|
|
1342
|
+
/**
|
|
1343
|
+
* A request that no route matched, handed whole to `FeatureService.hostRequest`:
|
|
1344
|
+
* the host has no route to decode it, so the path comes as received.
|
|
1345
|
+
*/
|
|
1346
|
+
export interface SdkHostRequest extends SdkPublicRequest {
|
|
1347
|
+
method: 'GET' | 'HEAD';
|
|
1348
|
+
/** As received, still percent-encoded, without the query string: `/` at the root, `/promo` below it. */
|
|
1349
|
+
path: string;
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1314
1352
|
export interface SdkPublicRouteOptions {
|
|
1315
1353
|
/** A ceiling per client address, on top of the host's own: `{ max, timeWindow: '1 minute' }`. */
|
|
1316
1354
|
rateLimit?: { max: number; timeWindow: string };
|
|
@@ -1380,7 +1418,8 @@ export type SdkPublicStreamHandler = (
|
|
|
1380
1418
|
* Paths are absolute (`/t.js`, `/api/t/b`); a path the host already serves
|
|
1381
1419
|
* is refused at boot. Every route is registered on every public listener.
|
|
1382
1420
|
* `/` belongs to the host: a page served at the root of a customer domain goes
|
|
1383
|
-
* through `FeatureService.domainRoot
|
|
1421
|
+
* through `FeatureService.domainRoot`, and every other path of a name you
|
|
1422
|
+
* serve whole through `FeatureService.hostRequest`.
|
|
1384
1423
|
*/
|
|
1385
1424
|
export interface SdkPublicApp {
|
|
1386
1425
|
get(path: string, opts: SdkPublicRouteOptions, handler: SdkPublicHandler): void;
|
|
@@ -1433,6 +1472,43 @@ export interface FeatureService {
|
|
|
1433
1472
|
* `'routes.public'` and manifest `domains.web`.
|
|
1434
1473
|
*/
|
|
1435
1474
|
domainRoot?(req: SdkPublicRequest, reply: SdkPublicReply, domain: SdkDomain): Promise<unknown>;
|
|
1475
|
+
/**
|
|
1476
|
+
* Names your feature serves WHOLE, outside any customer: a short domain of
|
|
1477
|
+
* the instance, read from your env (`go.example.com`). Each must match
|
|
1478
|
+
* `DOMAIN_HOST_PATTERN`, differ from the app's and the public surface's
|
|
1479
|
+
* hosts, and be claimed by one feature only: the boot refuses otherwise.
|
|
1480
|
+
* Reserved like the instance's own hosts: no workspace can declare them as
|
|
1481
|
+
* a domain, and the domain proxy never routes them (route them yourself to
|
|
1482
|
+
* the public listener). Requires `hostRequest`.
|
|
1483
|
+
*/
|
|
1484
|
+
ownHosts?: readonly string[];
|
|
1485
|
+
/**
|
|
1486
|
+
* A listener of your own, on this port, beside the app's and the public
|
|
1487
|
+
* surface's: the host serves there your public routes and your
|
|
1488
|
+
* `hostRequest`, for your `ownHosts` and your verified web domains, and
|
|
1489
|
+
* nothing of anyone else. None of your routes is mounted on the other
|
|
1490
|
+
* listeners, and the domain proxy sends your domains here: what you serve
|
|
1491
|
+
* shares no port with the instance's own names. Read the port from your
|
|
1492
|
+
* env; leave it out to stay on the public surface. Requires `ownHosts` and
|
|
1493
|
+
* `hostRequest`; a port another listener holds is refused at boot.
|
|
1494
|
+
*/
|
|
1495
|
+
ownListener?: { port: number };
|
|
1496
|
+
/**
|
|
1497
|
+
* Every GET or HEAD that no route matched, root included, on one of your
|
|
1498
|
+
* `ownHosts` (`domain` is `null`) or on one of YOUR verified web domains
|
|
1499
|
+
* (`domain` is that domain): for names whose paths are yours to define
|
|
1500
|
+
* (`go.example.com/promo`). Behind the maintenance gate, rate-limited by
|
|
1501
|
+
* the host. Your routes from `publicRoutes` still win where they match.
|
|
1502
|
+
* When several features verified the same name, the first installed that
|
|
1503
|
+
* answers the path takes it (`domainRoot` for `/`, `hostRequest` for any).
|
|
1504
|
+
* Exclusive with `domainRoot`. Requires capability `'routes.public'` and,
|
|
1505
|
+
* when your manifest declares `domains`, `domains.web`.
|
|
1506
|
+
*/
|
|
1507
|
+
hostRequest?(
|
|
1508
|
+
req: SdkHostRequest,
|
|
1509
|
+
reply: SdkPublicReply,
|
|
1510
|
+
domain: SdkDomain | null
|
|
1511
|
+
): Promise<unknown>;
|
|
1436
1512
|
/**
|
|
1437
1513
|
* Your `stock` items that a plan just paused or resumed, once written: for
|
|
1438
1514
|
* what you hold OPEN (a connection, a session, a timer). What you run on
|
|
@@ -1510,6 +1586,8 @@ export interface FeatureServiceDeps<Repo = unknown> {
|
|
|
1510
1586
|
pauses: SdkPlanPauses;
|
|
1511
1587
|
/** The devices' telemetry, sessionless (capability `'telemetry.read'`). */
|
|
1512
1588
|
telemetry: SdkTelemetry;
|
|
1589
|
+
/** Where a client address comes from (capability `'geoip'`). */
|
|
1590
|
+
geo: SdkGeo;
|
|
1513
1591
|
/** Live invalidation of your feature's resources, from a service. */
|
|
1514
1592
|
live: SdkLive;
|
|
1515
1593
|
/**
|
|
@@ -1693,11 +1771,16 @@ export interface SdkE2eContext<Repo = unknown> {
|
|
|
1693
1771
|
* dispatcher. Rejects with a `FeatureError` carrying the server's code.
|
|
1694
1772
|
*/
|
|
1695
1773
|
send<T = unknown>(command: string, input: unknown, opts?: { workspaceId?: number }): Promise<T>;
|
|
1696
|
-
/**
|
|
1774
|
+
/**
|
|
1775
|
+
* A sessionless request to this server's own listener: what a visitor's
|
|
1776
|
+
* browser sends to a public route. Redirects are not followed: a 302 comes
|
|
1777
|
+
* back as is, its target in `headers.location`. Header names are lowercase,
|
|
1778
|
+
* repeated ones joined by `, `.
|
|
1779
|
+
*/
|
|
1697
1780
|
fetch(
|
|
1698
1781
|
path: string,
|
|
1699
1782
|
init?: { method?: 'GET' | 'POST'; headers?: Record<string, string>; body?: string }
|
|
1700
|
-
): Promise<{ status: number; body: string }>;
|
|
1783
|
+
): Promise<{ status: number; body: string; headers: Readonly<Record<string, string>> }>;
|
|
1701
1784
|
/**
|
|
1702
1785
|
* Polls until `probe` answers something other than `null`, `undefined` or
|
|
1703
1786
|
* `false`, then resolves with it. Rejects after `timeoutMs` (default 10 s),
|
package/src/sdk/testing.ts
CHANGED
|
@@ -810,6 +810,8 @@ export interface TestServiceOverrides<Repo> {
|
|
|
810
810
|
origins?: SdkOrigins;
|
|
811
811
|
/** Instants `telemetry.snapshot` answers (matched within a second). Default none. */
|
|
812
812
|
snapshots?: readonly SdkTelemetrySnapshot[];
|
|
813
|
+
/** What `geo.country` answers, by client address. Default none: every address is unknown. */
|
|
814
|
+
countries?: Readonly<Record<string, string>>;
|
|
813
815
|
/** The feature's domains, every workspace mixed. Default none. */
|
|
814
816
|
domains?: readonly SdkDomain[];
|
|
815
817
|
/** The named contracts the host holds (`deps.providers.get(key)`). */
|
|
@@ -899,6 +901,10 @@ export function createTestServiceDeps<Repo = undefined>(
|
|
|
899
901
|
isOnline: devices.isOnline
|
|
900
902
|
},
|
|
901
903
|
telemetry: recordingTelemetry(recorded, overrides.snapshots ?? []),
|
|
904
|
+
geo: {
|
|
905
|
+
country: (ip) => overrides.countries?.[ip] ?? null,
|
|
906
|
+
attribution: { text: 'IP Geolocation by DB-IP', url: 'https://db-ip.com' }
|
|
907
|
+
},
|
|
902
908
|
live: {
|
|
903
909
|
changed(workspaceId, topics) {
|
|
904
910
|
recorded.liveChanges.push(workspaceId);
|
|
@@ -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
|
+
}
|