@prosopo/user-access-policy 3.14.13 → 3.14.15

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 (65) hide show
  1. package/.turbo/turbo-build$colon$cjs.log +2 -5
  2. package/.turbo/turbo-build$colon$tsc.log +14 -17
  3. package/.turbo/turbo-build.log +3 -9
  4. package/CHANGELOG.md +36 -0
  5. package/LICENSE +201 -0
  6. package/package.json +83 -81
  7. package/src/.export.ts +0 -65
  8. package/src/api/.export.ts +0 -25
  9. package/src/api/accessRulesApiClient.ts +0 -13
  10. package/src/api/delete/.export.ts +0 -18
  11. package/src/api/delete/deleteAllRules.ts +0 -47
  12. package/src/api/delete/deleteRuleGroups.ts +0 -96
  13. package/src/api/delete/deleteRules.ts +0 -87
  14. package/src/api/read/.export.ts +0 -25
  15. package/src/api/read/fetchRules.ts +0 -96
  16. package/src/api/read/findRuleIds.ts +0 -97
  17. package/src/api/read/getMissingIds.ts +0 -81
  18. package/src/api/ruleApiRoutes.ts +0 -146
  19. package/src/api/rulesApiClient.ts +0 -154
  20. package/src/api/write/.export.ts +0 -15
  21. package/src/api/write/insertRules.ts +0 -185
  22. package/src/api/write/rehashRules.ts +0 -85
  23. package/src/classifyBrowser.ts +0 -77
  24. package/src/classifyOs.ts +0 -74
  25. package/src/headerMatch.ts +0 -180
  26. package/src/matchedRule.ts +0 -99
  27. package/src/mongoose/.export.ts +0 -15
  28. package/src/mongoose/mongooseRuleSchema.ts +0 -75
  29. package/src/redis/.export.ts +0 -17
  30. package/src/redis/reader/redisAggregate.ts +0 -157
  31. package/src/redis/reader/redisRulesQuery.ts +0 -268
  32. package/src/redis/reader/redisRulesReader.ts +0 -738
  33. package/src/redis/reader/redisRulesSplitQuery.ts +0 -234
  34. package/src/redis/redisClient.ts +0 -125
  35. package/src/redis/redisRuleIndex.ts +0 -121
  36. package/src/redis/redisRulesStorage.ts +0 -68
  37. package/src/redis/redisRulesWriter.ts +0 -172
  38. package/src/rule.ts +0 -122
  39. package/src/ruleInput/.export.ts +0 -19
  40. package/src/ruleInput/policyInput.ts +0 -120
  41. package/src/ruleInput/ruleInput.ts +0 -123
  42. package/src/ruleInput/userScopeInput.ts +0 -142
  43. package/src/ruleRecord.ts +0 -77
  44. package/src/rulesStorage.ts +0 -90
  45. package/src/tests/blockingRuleShapes.unit.test.ts +0 -244
  46. package/src/tests/classifyBrowser.unit.test.ts +0 -138
  47. package/src/tests/classifyOs.unit.test.ts +0 -97
  48. package/src/tests/headerMatch.unit.test.ts +0 -350
  49. package/src/tests/insertRulesEndpoint.unit.test.ts +0 -89
  50. package/src/tests/matchedRule.unit.test.ts +0 -184
  51. package/src/tests/policyInput.unit.test.ts +0 -218
  52. package/src/tests/redis/deferredPoolClause.benchmark.ts +0 -249
  53. package/src/tests/redis/reader/redisAggregate.unit.test.ts +0 -121
  54. package/src/tests/redis/reader/redisRulesQuery.unit.test.ts +0 -349
  55. package/src/tests/redis/reader/redisRulesSplitQuery.unit.test.ts +0 -297
  56. package/src/tests/redis/redisRulesReaderLoad.benchmark.integration.test.ts +0 -520
  57. package/src/tests/redis/redisRulesReaderRank.benchmark.integration.test.ts +0 -350
  58. package/src/tests/redis/redisRulesStorage.integration.test.ts +0 -1811
  59. package/src/tests/testLogger.ts +0 -38
  60. package/src/tests/transformRule.unit.test.ts +0 -345
  61. package/src/transformRule.ts +0 -133
  62. package/tsconfig.cjs.json +0 -41
  63. package/tsconfig.json +0 -47
  64. package/tsconfig.tsbuildinfo +0 -1
  65. package/tsconfig.types.json +0 -9
@@ -1,154 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import { ApiClient } from "@prosopo/api";
16
- import type { ApiEndpointResponse } from "@prosopo/api-route";
17
- import {
18
- type FetchRulesEndpointResponse,
19
- type FetchRulesOptions,
20
- fetchRulesResponse,
21
- } from "#policy/api/read/fetchRules.js";
22
- import {
23
- type RuleIdsEndpointResponse,
24
- ruleIdsResponse,
25
- } from "#policy/api/read/findRuleIds.js";
26
- import {
27
- type MissingIds,
28
- type MissingIdsEndpointResponse,
29
- missingIdsResponse,
30
- } from "#policy/api/read/getMissingIds.js";
31
- import type { AccessRulesFilterInput } from "#policy/ruleInput/ruleInput.js";
32
- import type { DeleteSiteGroups } from "./delete/deleteRuleGroups.js";
33
- import { accessRuleApiPaths } from "./ruleApiRoutes.js";
34
- import type { InsertRulesGroup } from "./write/insertRules.js";
35
-
36
- export class AccessRulesApiClient extends ApiClient {
37
- //// delete
38
-
39
- public deleteMany(
40
- filters: AccessRulesFilterInput[],
41
- jwt: string,
42
- ): Promise<ApiEndpointResponse> {
43
- return this.post(
44
- accessRuleApiPaths.DELETE_MANY,
45
- filters,
46
- this.getAuthHeaders(jwt),
47
- );
48
- }
49
-
50
- public deleteGroups(
51
- siteGroups: DeleteSiteGroups,
52
- jwt: string,
53
- ): Promise<ApiEndpointResponse> {
54
- return this.post(
55
- accessRuleApiPaths.DELETE_GROUPS,
56
- siteGroups,
57
- this.getAuthHeaders(jwt),
58
- );
59
- }
60
-
61
- public deleteAll(jwt: string): Promise<ApiEndpointResponse> {
62
- return this.post(
63
- accessRuleApiPaths.DELETE_ALL,
64
- {},
65
- this.getAuthHeaders(jwt),
66
- );
67
- }
68
-
69
- //// read
70
-
71
- public async getMissingIds(
72
- idsToCheck: MissingIds,
73
- jwt: string,
74
- ): Promise<MissingIdsEndpointResponse> {
75
- const endpointResponse: ApiEndpointResponse = await this.post(
76
- accessRuleApiPaths.GET_MISSING_IDS,
77
- idsToCheck,
78
- this.getAuthHeaders(jwt),
79
- );
80
-
81
- const parsedData = missingIdsResponse.safeParse(endpointResponse.data);
82
-
83
- return {
84
- ...endpointResponse,
85
- data: parsedData.success ? parsedData.data : undefined,
86
- };
87
- }
88
-
89
- public async fetchMany(
90
- fetchOptions: FetchRulesOptions,
91
- jwt: string,
92
- ): Promise<FetchRulesEndpointResponse> {
93
- const endpointResponse: ApiEndpointResponse = await this.post(
94
- accessRuleApiPaths.FETCH_MANY,
95
- fetchOptions,
96
- this.getAuthHeaders(jwt),
97
- );
98
-
99
- const parsedData = fetchRulesResponse.safeParse(endpointResponse.data);
100
-
101
- return {
102
- ...endpointResponse,
103
- data: parsedData.success ? parsedData.data : undefined,
104
- };
105
- }
106
-
107
- public async findIds(
108
- filters: AccessRulesFilterInput[],
109
- jwt: string,
110
- ): Promise<RuleIdsEndpointResponse> {
111
- const endpointResponse: ApiEndpointResponse = await this.post(
112
- accessRuleApiPaths.FIND_IDS,
113
- filters,
114
- this.getAuthHeaders(jwt),
115
- );
116
-
117
- const parsedData = ruleIdsResponse.safeParse(endpointResponse.data);
118
-
119
- return {
120
- ...endpointResponse,
121
- data: parsedData.success ? parsedData.data : undefined,
122
- };
123
- }
124
-
125
- //// write
126
-
127
- public async rehashAll(jwt: string): Promise<ApiEndpointResponse> {
128
- return this.post(
129
- accessRuleApiPaths.REHASH_ALL,
130
- {},
131
- this.getAuthHeaders(jwt),
132
- );
133
- }
134
-
135
- public insertMany(
136
- ruleGroups: InsertRulesGroup[],
137
- jwt: string,
138
- ): Promise<ApiEndpointResponse> {
139
- return this.post(
140
- accessRuleApiPaths.INSERT_MANY,
141
- ruleGroups,
142
- this.getAuthHeaders(jwt),
143
- );
144
- }
145
-
146
- protected getAuthHeaders(jwt: string): RequestInit {
147
- return {
148
- headers: {
149
- "Prosopo-Site-Key": this.account,
150
- Authorization: `Bearer ${jwt}`,
151
- },
152
- };
153
- }
154
- }
@@ -1,15 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- export type { InsertRulesGroup } from "./insertRules.js";
@@ -1,185 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import {
16
- type ApiEndpoint,
17
- type ApiEndpointResponse,
18
- ApiEndpointResponseStatus,
19
- } from "@prosopo/api-route";
20
- import type { AllKeys } from "@prosopo/common";
21
- import { LogLevel, type Logger } from "@prosopo/logger";
22
- import { type ZodType, type ZodTypeDef, z } from "zod";
23
- import type {
24
- AccessPolicy,
25
- AccessRule,
26
- PolicyScope,
27
- UserScope,
28
- } from "#policy/rule.js";
29
- import {
30
- accessPolicyInput,
31
- policyScopeInput,
32
- sanitizeAccessPolicy,
33
- } from "#policy/ruleInput/policyInput.js";
34
- import {
35
- type UserScopeInput,
36
- userScopeInput,
37
- } from "#policy/ruleInput/userScopeInput.js";
38
- import type {
39
- AccessRuleEntry,
40
- AccessRulesWriter,
41
- } from "#policy/rulesStorage.js";
42
-
43
- export type InsertRulesGroup = {
44
- accessPolicy: AccessPolicy;
45
- userScopes: UserScopeInput[];
46
- // a single client may have multiple siteKeys,
47
- // so for batch requests we take multiple policyScopes as apply all the rules to every scope
48
- policyScopes?: PolicyScope[];
49
- groupId?: string;
50
- expiresUnixTimestamp?: number;
51
- };
52
-
53
- type ParsedInsertRulesGroup = InsertRulesGroup & {
54
- userScopes: UserScope[];
55
- };
56
-
57
- type ParsedInsertRuleGroups = ParsedInsertRulesGroup[];
58
-
59
- // Input position widened to `unknown` because `accessPolicyInput` uses
60
- // `z.preprocess` on `deferToVerify` for Redis string round-tripping.
61
- type InsertRulesSchema = ZodType<InsertRulesGroup[], ZodTypeDef, unknown>;
62
-
63
- export class InsertRulesEndpoint implements ApiEndpoint<InsertRulesSchema> {
64
- public constructor(
65
- private readonly accessRulesWriter: AccessRulesWriter,
66
- private readonly logger: Logger,
67
- ) {}
68
-
69
- public getRequestArgsSchema(): InsertRulesSchema {
70
- return z.array(
71
- z.object({
72
- accessPolicy: accessPolicyInput,
73
- policyScopes: z.array(policyScopeInput).optional(),
74
- groupId: z.string().optional(),
75
- userScopes: z.array(userScopeInput),
76
- expiresUnixTimestamp: z.number().optional(),
77
- } satisfies AllKeys<InsertRulesGroup>),
78
- );
79
- }
80
-
81
- async processRequest(
82
- args: ParsedInsertRuleGroups,
83
- logger?: Logger,
84
- ): Promise<ApiEndpointResponse> {
85
- const log = logger ?? this.logger;
86
-
87
- const timeoutPromise = new Promise<ApiEndpointResponse>((resolve) => {
88
- setTimeout(() => {
89
- resolve({
90
- status: ApiEndpointResponseStatus.PROCESSING,
91
- });
92
- }, 5000);
93
- });
94
-
95
- const userScopesCount = args.reduce(
96
- (userScopesCount, group) => userScopesCount + group.userScopes.length,
97
- 0,
98
- );
99
-
100
- const createRulesPromise = this.createRuleGroups(args)
101
- .then((insertedIds) => {
102
- log.info(() => ({
103
- msg: "Endpoint inserted access rules",
104
- data: {
105
- userScopesCount: userScopesCount,
106
- insertedCount: insertedIds.length,
107
- uniqueIdsCount: new Set(insertedIds).size,
108
- },
109
- }));
110
-
111
- log.debug(() => ({
112
- msg: "Inserted access rules details",
113
- data: {
114
- insertedIds,
115
- input: args,
116
- },
117
- }));
118
-
119
- return {
120
- status: ApiEndpointResponseStatus.SUCCESS,
121
- };
122
- })
123
- .catch((error) => {
124
- if (LogLevel.enum.debug === log.getLogLevel()) {
125
- log.error(() => ({
126
- err: error,
127
- data: { args },
128
- msg: "Failed to insert access rules",
129
- }));
130
- }
131
- return {
132
- status: ApiEndpointResponseStatus.FAIL,
133
- };
134
- });
135
-
136
- // Whichever finishes first: timeout or actual rule creation
137
- return Promise.race([timeoutPromise, createRulesPromise]);
138
- }
139
-
140
- protected async createRuleGroups(
141
- groups: ParsedInsertRuleGroups,
142
- ): Promise<string[]> {
143
- const ruleIdPromises = groups.map((group) => this.createRulesGroup(group));
144
-
145
- const ruleIdSets = await Promise.all(ruleIdPromises);
146
-
147
- return ruleIdSets.flat();
148
- }
149
-
150
- protected async createRulesGroup(
151
- group: ParsedInsertRulesGroup,
152
- ): Promise<string[]> {
153
- const ruleEntries: AccessRuleEntry[] = [];
154
- const policyScopes = group.policyScopes || [];
155
- // Sanitize the access policy to remove unnecessary fields from block policies
156
- const sanitizedPolicy = sanitizeAccessPolicy(group.accessPolicy);
157
-
158
- for (const userScope of group.userScopes) {
159
- const ruleBase: AccessRule = {
160
- ...sanitizedPolicy,
161
- ...userScope,
162
- ...(group.groupId ? { groupId: group.groupId } : {}),
163
- };
164
-
165
- if (policyScopes.length > 0) {
166
- for (const policyScope of policyScopes) {
167
- ruleEntries.push({
168
- rule: {
169
- ...ruleBase,
170
- ...policyScope,
171
- },
172
- expiresUnixTimestamp: group.expiresUnixTimestamp,
173
- });
174
- }
175
- } else {
176
- ruleEntries.push({
177
- rule: ruleBase,
178
- expiresUnixTimestamp: group.expiresUnixTimestamp,
179
- });
180
- }
181
- }
182
-
183
- return this.accessRulesWriter.insertRules(ruleEntries);
184
- }
185
- }
@@ -1,85 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- import {
16
- type ApiEndpoint,
17
- type ApiEndpointResponse,
18
- ApiEndpointResponseStatus,
19
- } from "@prosopo/api-route";
20
- import type { Logger } from "@prosopo/logger";
21
- import type { AccessRulesStorage } from "#policy/rulesStorage.js";
22
-
23
- export class RehashRulesEndpoint implements ApiEndpoint<undefined> {
24
- public constructor(
25
- private readonly accessRulesStorage: AccessRulesStorage,
26
- private readonly logger: Logger,
27
- ) {}
28
-
29
- public getRequestArgsSchema(): undefined {}
30
-
31
- async processRequest(logger?: Logger): Promise<ApiEndpointResponse> {
32
- const log = logger ?? this.logger;
33
- await this.accessRulesStorage.fetchAllRuleIds(async (ruleIds: string[]) => {
34
- log.info(() => ({
35
- msg: "Fetched rule ids batch",
36
- data: {
37
- count: ruleIds.length,
38
- ruleIds,
39
- },
40
- }));
41
-
42
- const ruleEntries = await this.accessRulesStorage.fetchRules(ruleIds);
43
-
44
- log.info(() => ({
45
- msg: "Fetched rules",
46
- data: {
47
- count: ruleEntries.length,
48
- },
49
- }));
50
-
51
- if (ruleEntries.length !== ruleIds.length) {
52
- log.warn(() => ({
53
- msg: "Fetched rules count is not equal to the requested count",
54
- data: {
55
- fetchedCount: ruleEntries.length,
56
- requestedCount: ruleIds.length,
57
- },
58
- }));
59
- }
60
-
61
- await this.accessRulesStorage.deleteRules(ruleIds);
62
-
63
- log.info(() => ({
64
- msg: "Deleted rules",
65
- data: {
66
- count: ruleIds.length,
67
- },
68
- }));
69
-
70
- await this.accessRulesStorage.insertRules(ruleEntries);
71
-
72
- log.info(() => ({
73
- msg: "Inserted rules",
74
- data: {
75
- count: ruleEntries.length,
76
- },
77
- }));
78
- });
79
-
80
- return {
81
- status: ApiEndpointResponseStatus.SUCCESS,
82
- data: {},
83
- };
84
- }
85
- }
@@ -1,77 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- /**
16
- * Kept in step with `@prosopo/decision-machines`' `uaClassify` — as `classifyOs`
17
- * is — but defined here because the provider request path cannot depend on that
18
- * package.
19
- */
20
- export const BROWSER_NAMES = [
21
- "chrome",
22
- "safari",
23
- "firefox",
24
- "edge",
25
- "opera",
26
- "samsung_internet",
27
- "wechat",
28
- "facebook",
29
- "instagram",
30
- "ie",
31
- "unknown",
32
- ] as const;
33
-
34
- export type BrowserName = (typeof BROWSER_NAMES)[number];
35
-
36
- /**
37
- * Branch order is load-bearing: every browser below Chrome also carries a
38
- * `chrome/` token, and Safari's signature appears in nearly every WebKit UA.
39
- *
40
- * Reads the User-Agent rather than the `sec-ch-ua` client hint because a client
41
- * can simply omit client hints, but stripping the UA breaks far more.
42
- */
43
- export const classifyBrowser = (userAgent: string | undefined): BrowserName => {
44
- const ua = (userAgent || "").toLowerCase();
45
-
46
- if (/\bedg(?:e|a|ios)?\//.test(ua)) {
47
- return "edge";
48
- }
49
- if (/samsungbrowser/.test(ua)) {
50
- return "samsung_internet";
51
- }
52
- if (/\bopr\/|opera/.test(ua)) {
53
- return "opera";
54
- }
55
- if (/micromessenger/.test(ua)) {
56
- return "wechat";
57
- }
58
- if (/fban|fbav|fbios/.test(ua)) {
59
- return "facebook";
60
- }
61
- if (/instagram/.test(ua)) {
62
- return "instagram";
63
- }
64
- if (/firefox|fxios/.test(ua)) {
65
- return "firefox";
66
- }
67
- if (/msie|trident/.test(ua)) {
68
- return "ie";
69
- }
70
- if (/\bchrome\/|\bcrios\//.test(ua)) {
71
- return "chrome";
72
- }
73
- if (/safari\//.test(ua)) {
74
- return "safari";
75
- }
76
- return "unknown";
77
- };
package/src/classifyOs.ts DELETED
@@ -1,74 +0,0 @@
1
- // Copyright 2021-2026 Prosopo (UK) Ltd.
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
-
15
- /**
16
- * The operating systems the classifier can resolve a request to. Kept
17
- * deliberately in step with the OS vocabulary in
18
- * `@prosopo/decision-machines`' `uaClassify` (so a routing-rule `osNameIn` and
19
- * an access-rule `os` agree on the same names), but defined here because the
20
- * provider / user-access-policy request path cannot depend on the
21
- * decision-machines package.
22
- *
23
- * `unknown` is the catch-all when no signature matches. It is a first-class
24
- * value so an allow-list ("only let Windows through") can block unrecognised
25
- * User-Agents instead of silently passing them.
26
- */
27
- export const OS_NAMES = [
28
- "windows",
29
- "macos",
30
- "ios",
31
- "android",
32
- "linux",
33
- "unknown",
34
- ] as const;
35
-
36
- export type OsName = (typeof OS_NAMES)[number];
37
-
38
- /**
39
- * Classify the operating system from a raw User-Agent string. Pure — no
40
- * navigator/window/DOM dependence — so it is safe to call on the provider's
41
- * server-side request path.
42
- *
43
- * Detection order matches `uaClassify.classifyUserAgent`: iOS (iphone/ipad/
44
- * ipod) is tested before the generic mac signature, and Android before Linux,
45
- * because those User-Agents contain the more general token too. Detection is
46
- * conservative — anything unrecognised returns `unknown` rather than guessing,
47
- * so an `os === "ios"` rule never fires on a UA we don't understand.
48
- *
49
- * The classification is driven off the full User-Agent rather than the
50
- * `sec-ch-ua-platform` client hint on purpose: a client can simply omit client
51
- * hints, but stripping the User-Agent breaks far more, so the UA is the more
52
- * reliable signal for an OS-restriction rule that is meant to be hard to
53
- * bypass.
54
- */
55
- export const classifyOs = (userAgent: string | undefined): OsName => {
56
- const ua = (userAgent || "").toLowerCase();
57
-
58
- if (/iphone|ipad|ipod/.test(ua)) {
59
- return "ios";
60
- }
61
- if (/android/.test(ua)) {
62
- return "android";
63
- }
64
- if (/windows/.test(ua)) {
65
- return "windows";
66
- }
67
- if (/macintosh|mac os/.test(ua)) {
68
- return "macos";
69
- }
70
- if (/linux/.test(ua)) {
71
- return "linux";
72
- }
73
- return "unknown";
74
- };