@rawdash/connector-auth0 0.0.1 → 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.
- package/LICENSE +202 -0
- package/README.md +6 -6
- package/dist/index.d.ts +7 -7
- package/dist/index.js +63 -34
- package/dist/index.js.map +1 -1
- package/package.json +13 -13
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
[](https://www.npmjs.com/package/@rawdash/connector-auth0)
|
|
6
6
|
[](https://github.com/rawdash/rawdash/blob/main/LICENSE)
|
|
7
7
|
|
|
8
|
-
Sync users, login events, and daily
|
|
8
|
+
Sync users, login events, and daily login / signup metrics from an Auth0 tenant for identity, sign-up, and failed-login dashboards.
|
|
9
9
|
|
|
10
10
|
## Install
|
|
11
11
|
|
|
@@ -31,7 +31,7 @@ OAuth 2.0 client-credentials flow against a Machine-to-Machine application autho
|
|
|
31
31
|
| `clientId` | string | Yes | Client ID of the Auth0 Machine-to-Machine application authorized to call the Management API. |
|
|
32
32
|
| `clientSecret` | secret | Yes | Client secret of the Auth0 Machine-to-Machine application. Stored as a secret. |
|
|
33
33
|
| `resources` | array | No | Which Auth0 resources to sync. Omit to sync all of them. The M2M application only needs the Management API scopes for the resources listed here (read:users, read:logs, read:stats). |
|
|
34
|
-
| `statsLookbackDays` | number | No | How many days of daily
|
|
34
|
+
| `statsLookbackDays` | number | No | How many days of daily logins / signups stats to refresh on each sync. Defaults to 30; the Auth0 Daily Stats endpoint accepts an arbitrary from/to range. |
|
|
35
35
|
|
|
36
36
|
## Resources
|
|
37
37
|
|
|
@@ -46,14 +46,14 @@ OAuth 2.0 client-credentials flow against a Machine-to-Machine application autho
|
|
|
46
46
|
- `createdAt`: When the user record was created (Unix ms).
|
|
47
47
|
- **`auth0_login_event`** _(event)_ - Login / authentication events from the Auth0 Logs endpoint. One event per log row of type s (success), f (failure), seacft (token exchange success), or fp (failed change password).
|
|
48
48
|
- Endpoint: `GET /api/v2/logs`
|
|
49
|
-
- Uses
|
|
49
|
+
- Uses checkpoint pagination (from = last seen log_id, take = page size) and reads every page until the endpoint returns no more rows, so a sync is not capped at 1000 events. Incremental syncs resume from the last ingested log_id; the type filter (and any since bound) is applied client-side because the checkpoint method ignores q / sort / page.
|
|
50
50
|
- `logId`: Auth0 log row id.
|
|
51
51
|
- `type`: Auth0 log type (s, f, seacft, fp).
|
|
52
52
|
- `userId`: Auth0 user_id the event belongs to (may be null).
|
|
53
53
|
- `ip`: Source IP of the login attempt.
|
|
54
54
|
- `connection`: Connection name used for the login.
|
|
55
55
|
- `strategy`: Identity provider strategy (e.g. auth0, google-oauth2, samlp).
|
|
56
|
-
- **`auth0_daily_active_users`** _(metric)_ - Daily
|
|
56
|
+
- **`auth0_daily_active_users`** _(metric)_ - Daily login and signup counts from the Auth0 Daily Stats endpoint, one sample per day for the configured lookback window. This is a logins/signups activity proxy, not a count of distinct active users.
|
|
57
57
|
- Endpoint: `GET /api/v2/stats/daily`
|
|
58
58
|
- Unit: count
|
|
59
59
|
- Granularity: 1d
|
|
@@ -120,11 +120,11 @@ Auth0 publishes X-RateLimit-Limit / X-RateLimit-Remaining / X-RateLimit-Reset re
|
|
|
120
120
|
|
|
121
121
|
- User enumeration uses offset pagination (page/per_page) and is capped at the first 1000 users per sync; tenants with more than 1000 users updated since the last run should increase sync frequency so each window stays under the cap.
|
|
122
122
|
- Action / hook / branding configuration objects are out of scope.
|
|
123
|
-
- Only Auth0 tenants on the
|
|
123
|
+
- Only Auth0 tenants on the `*.auth0.com` hostname suffix are supported; custom-domain tenants must still expose a `*.auth0.com` hostname for the Management API.
|
|
124
124
|
|
|
125
125
|
## Links
|
|
126
126
|
|
|
127
|
-
- [Rawdash docs](https://rawdash.dev/docs/connectors
|
|
127
|
+
- [Rawdash docs](https://rawdash.dev/docs/connectors)
|
|
128
128
|
- [Auth0 API docs](https://auth0.com/docs/api/management/v2)
|
|
129
129
|
- [GitHub](https://github.com/rawdash/rawdash)
|
|
130
130
|
|
package/dist/index.d.ts
CHANGED
|
@@ -104,7 +104,7 @@ declare const auth0Resources: {
|
|
|
104
104
|
}];
|
|
105
105
|
readonly description: "Login / authentication events from the Auth0 Logs endpoint. One event per log row of type s (success), f (failure), seacft (token exchange success), or fp (failed change password).";
|
|
106
106
|
readonly endpoint: "GET /api/v2/logs";
|
|
107
|
-
readonly notes: "Uses
|
|
107
|
+
readonly notes: "Uses checkpoint pagination (from = last seen log_id, take = page size) and reads every page until the endpoint returns no more rows, so a sync is not capped at 1000 events. Incremental syncs resume from the last ingested log_id; the type filter (and any since bound) is applied client-side because the checkpoint method ignores q / sort / page.";
|
|
108
108
|
readonly fields: [{
|
|
109
109
|
readonly name: "logId";
|
|
110
110
|
readonly description: "Auth0 log row id.";
|
|
@@ -141,7 +141,7 @@ declare const auth0Resources: {
|
|
|
141
141
|
};
|
|
142
142
|
readonly auth0_daily_active_users: {
|
|
143
143
|
readonly shape: "metric";
|
|
144
|
-
readonly description: "Daily
|
|
144
|
+
readonly description: "Daily login and signup counts from the Auth0 Daily Stats endpoint, one sample per day for the configured lookback window. This is a logins/signups activity proxy, not a count of distinct active users.";
|
|
145
145
|
readonly endpoint: "GET /api/v2/stats/daily";
|
|
146
146
|
readonly unit: "count";
|
|
147
147
|
readonly granularity: "1d";
|
|
@@ -154,7 +154,6 @@ declare const auth0Resources: {
|
|
|
154
154
|
date: z.ZodString;
|
|
155
155
|
logins: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
156
156
|
signups: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
157
|
-
leaked_passwords: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
158
157
|
updated_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
159
158
|
created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
160
159
|
}, z.core.$strip>>;
|
|
@@ -236,7 +235,7 @@ declare class Auth0Connector extends BaseConnector<Auth0Settings, Auth0Credentia
|
|
|
236
235
|
}];
|
|
237
236
|
readonly description: "Login / authentication events from the Auth0 Logs endpoint. One event per log row of type s (success), f (failure), seacft (token exchange success), or fp (failed change password).";
|
|
238
237
|
readonly endpoint: "GET /api/v2/logs";
|
|
239
|
-
readonly notes: "Uses
|
|
238
|
+
readonly notes: "Uses checkpoint pagination (from = last seen log_id, take = page size) and reads every page until the endpoint returns no more rows, so a sync is not capped at 1000 events. Incremental syncs resume from the last ingested log_id; the type filter (and any since bound) is applied client-side because the checkpoint method ignores q / sort / page.";
|
|
240
239
|
readonly fields: [{
|
|
241
240
|
readonly name: "logId";
|
|
242
241
|
readonly description: "Auth0 log row id.";
|
|
@@ -273,7 +272,7 @@ declare class Auth0Connector extends BaseConnector<Auth0Settings, Auth0Credentia
|
|
|
273
272
|
};
|
|
274
273
|
readonly auth0_daily_active_users: {
|
|
275
274
|
readonly shape: "metric";
|
|
276
|
-
readonly description: "Daily
|
|
275
|
+
readonly description: "Daily login and signup counts from the Auth0 Daily Stats endpoint, one sample per day for the configured lookback window. This is a logins/signups activity proxy, not a count of distinct active users.";
|
|
277
276
|
readonly endpoint: "GET /api/v2/stats/daily";
|
|
278
277
|
readonly unit: "count";
|
|
279
278
|
readonly granularity: "1d";
|
|
@@ -286,7 +285,6 @@ declare class Auth0Connector extends BaseConnector<Auth0Settings, Auth0Credentia
|
|
|
286
285
|
date: z.ZodString;
|
|
287
286
|
logins: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
288
287
|
signups: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
289
|
-
leaked_passwords: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
290
288
|
updated_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
291
289
|
created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
292
290
|
}, z.core.$strip>>;
|
|
@@ -339,7 +337,6 @@ declare class Auth0Connector extends BaseConnector<Auth0Settings, Auth0Credentia
|
|
|
339
337
|
date: z.ZodString;
|
|
340
338
|
logins: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
341
339
|
signups: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
342
|
-
leaked_passwords: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
|
|
343
340
|
updated_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
344
341
|
created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
345
342
|
}, z.core.$strip>>;
|
|
@@ -357,6 +354,7 @@ declare class Auth0Connector extends BaseConnector<Auth0Settings, Auth0Credentia
|
|
|
357
354
|
};
|
|
358
355
|
};
|
|
359
356
|
private accessToken;
|
|
357
|
+
private accessTokenExpiry;
|
|
360
358
|
private baseUrl;
|
|
361
359
|
private audience;
|
|
362
360
|
private refreshAccessToken;
|
|
@@ -367,7 +365,9 @@ declare class Auth0Connector extends BaseConnector<Auth0Settings, Auth0Credentia
|
|
|
367
365
|
private buildLogsUrl;
|
|
368
366
|
private buildDailyStatsUrl;
|
|
369
367
|
private fetchUsersPage;
|
|
368
|
+
private logCheckpoint;
|
|
370
369
|
private fetchLogsPage;
|
|
370
|
+
private lastIngestedLogId;
|
|
371
371
|
private fetchDailyStats;
|
|
372
372
|
private writeUsers;
|
|
373
373
|
private writeLogs;
|
package/dist/index.js
CHANGED
|
@@ -101,9 +101,9 @@ var configFields = defineConfigFields(
|
|
|
101
101
|
label: "Resources",
|
|
102
102
|
description: "Which Auth0 resources to sync. Omit to sync all of them. The M2M application only needs the Management API scopes for the resources listed here (read:users, read:logs, read:stats)."
|
|
103
103
|
}),
|
|
104
|
-
statsLookbackDays: z.number().int().positive().
|
|
104
|
+
statsLookbackDays: z.number().int().positive().optional().meta({
|
|
105
105
|
label: "Stats lookback (days)",
|
|
106
|
-
description: "How many days of daily
|
|
106
|
+
description: "How many days of daily logins / signups stats to refresh on each sync. Defaults to 30; the Auth0 Daily Stats endpoint accepts an arbitrary from/to range.",
|
|
107
107
|
placeholder: "30"
|
|
108
108
|
})
|
|
109
109
|
})
|
|
@@ -112,7 +112,7 @@ var doc = defineConnectorDoc({
|
|
|
112
112
|
displayName: "Auth0",
|
|
113
113
|
category: "security",
|
|
114
114
|
brandColor: "#EB5424",
|
|
115
|
-
tagline: "Sync users, login events, and daily
|
|
115
|
+
tagline: "Sync users, login events, and daily login / signup metrics from an Auth0 tenant for identity, sign-up, and failed-login dashboards.",
|
|
116
116
|
vendor: {
|
|
117
117
|
name: "Auth0",
|
|
118
118
|
domain: "auth0.com",
|
|
@@ -133,7 +133,7 @@ var doc = defineConnectorDoc({
|
|
|
133
133
|
limitations: [
|
|
134
134
|
"User enumeration uses offset pagination (page/per_page) and is capped at the first 1000 users per sync; tenants with more than 1000 users updated since the last run should increase sync frequency so each window stays under the cap.",
|
|
135
135
|
"Action / hook / branding configuration objects are out of scope.",
|
|
136
|
-
"Only Auth0 tenants on the
|
|
136
|
+
"Only Auth0 tenants on the `*.auth0.com` hostname suffix are supported; custom-domain tenants must still expose a `*.auth0.com` hostname for the Management API."
|
|
137
137
|
]
|
|
138
138
|
});
|
|
139
139
|
var auth0Credentials = {
|
|
@@ -207,7 +207,6 @@ var dailyStatSchema = z.object({
|
|
|
207
207
|
date: z.string(),
|
|
208
208
|
logins: z.number().nullish(),
|
|
209
209
|
signups: z.number().nullish(),
|
|
210
|
-
leaked_passwords: z.number().nullish(),
|
|
211
210
|
updated_at: z.string().nullish(),
|
|
212
211
|
created_at: z.string().nullish()
|
|
213
212
|
});
|
|
@@ -261,7 +260,7 @@ var auth0Resources = defineResources({
|
|
|
261
260
|
],
|
|
262
261
|
description: "Login / authentication events from the Auth0 Logs endpoint. One event per log row of type s (success), f (failure), seacft (token exchange success), or fp (failed change password).",
|
|
263
262
|
endpoint: "GET /api/v2/logs",
|
|
264
|
-
notes: "Uses
|
|
263
|
+
notes: "Uses checkpoint pagination (from = last seen log_id, take = page size) and reads every page until the endpoint returns no more rows, so a sync is not capped at 1000 events. Incremental syncs resume from the last ingested log_id; the type filter (and any since bound) is applied client-side because the checkpoint method ignores q / sort / page.",
|
|
265
264
|
fields: [
|
|
266
265
|
{ name: "logId", description: "Auth0 log row id." },
|
|
267
266
|
{
|
|
@@ -286,7 +285,7 @@ var auth0Resources = defineResources({
|
|
|
286
285
|
},
|
|
287
286
|
[DAILY_METRIC]: {
|
|
288
287
|
shape: "metric",
|
|
289
|
-
description: "Daily
|
|
288
|
+
description: "Daily login and signup counts from the Auth0 Daily Stats endpoint, one sample per day for the configured lookback window. This is a logins/signups activity proxy, not a count of distinct active users.",
|
|
290
289
|
endpoint: "GET /api/v2/stats/daily",
|
|
291
290
|
unit: "count",
|
|
292
291
|
granularity: "1d",
|
|
@@ -348,6 +347,7 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
348
347
|
id = id;
|
|
349
348
|
credentials = auth0Credentials;
|
|
350
349
|
accessToken = null;
|
|
350
|
+
accessTokenExpiry = 0;
|
|
351
351
|
baseUrl() {
|
|
352
352
|
return `https://${this.settings.domain}`;
|
|
353
353
|
}
|
|
@@ -373,17 +373,21 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
373
373
|
signal
|
|
374
374
|
}
|
|
375
375
|
);
|
|
376
|
-
|
|
376
|
+
const token = res.body.access_token;
|
|
377
|
+
const expiresIn = res.body.expires_in ?? 3600;
|
|
378
|
+
this.accessToken = token;
|
|
379
|
+
this.accessTokenExpiry = Date.now() + (expiresIn - 60) * 1e3;
|
|
380
|
+
return token;
|
|
377
381
|
}
|
|
378
382
|
async getAccessToken(signal) {
|
|
379
|
-
if (!this.accessToken) {
|
|
380
|
-
|
|
383
|
+
if (!this.accessToken || Date.now() >= this.accessTokenExpiry) {
|
|
384
|
+
return this.refreshAccessToken(signal);
|
|
381
385
|
}
|
|
382
386
|
return this.accessToken;
|
|
383
387
|
}
|
|
384
|
-
async apiGet(url, resource, signal) {
|
|
388
|
+
async apiGet(url, resource, signal, retried = false) {
|
|
385
389
|
const token = await this.getAccessToken(signal);
|
|
386
|
-
|
|
390
|
+
const res = await this.get(url, {
|
|
387
391
|
resource,
|
|
388
392
|
headers: {
|
|
389
393
|
Authorization: `Bearer ${token}`,
|
|
@@ -393,6 +397,12 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
393
397
|
rateLimit: auth0RateLimit,
|
|
394
398
|
signal
|
|
395
399
|
});
|
|
400
|
+
if (res.status === 401 && !retried) {
|
|
401
|
+
this.accessToken = null;
|
|
402
|
+
this.accessTokenExpiry = 0;
|
|
403
|
+
return this.apiGet(url, resource, signal, true);
|
|
404
|
+
}
|
|
405
|
+
return res;
|
|
396
406
|
}
|
|
397
407
|
parsePageCursor(page) {
|
|
398
408
|
if (!page) {
|
|
@@ -417,18 +427,12 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
417
427
|
}
|
|
418
428
|
return u.toString();
|
|
419
429
|
}
|
|
420
|
-
buildLogsUrl(
|
|
430
|
+
buildLogsUrl(from) {
|
|
421
431
|
const u = new URL(`${this.baseUrl()}/api/v2/logs`);
|
|
422
|
-
u.searchParams.set("
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
u.searchParams.set("sort", "date:1");
|
|
426
|
-
const typeClause = LOG_EVENT_TYPES.map((t) => `type:"${t}"`).join(" OR ");
|
|
427
|
-
const clauses = [`(${typeClause})`];
|
|
428
|
-
if (options.since) {
|
|
429
|
-
clauses.push(`date:[${escapeLuceneRange(options.since)} TO *]`);
|
|
432
|
+
u.searchParams.set("take", String(PAGE_SIZE));
|
|
433
|
+
if (from) {
|
|
434
|
+
u.searchParams.set("from", from);
|
|
430
435
|
}
|
|
431
|
-
u.searchParams.set("q", clauses.join(" AND "));
|
|
432
436
|
return u.toString();
|
|
433
437
|
}
|
|
434
438
|
buildDailyStatsUrl(options) {
|
|
@@ -459,14 +463,29 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
459
463
|
const hasMore = length >= PAGE_SIZE && nextPage < MAX_USER_PAGES;
|
|
460
464
|
return { items: users, next: hasMore ? String(nextPage) : null };
|
|
461
465
|
}
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
466
|
+
logCheckpoint(log) {
|
|
467
|
+
return log.log_id ?? log._id;
|
|
468
|
+
}
|
|
469
|
+
async fetchLogsPage(from, signal) {
|
|
470
|
+
const url = this.buildLogsUrl(from);
|
|
465
471
|
const res = await this.apiGet(url, "logs", signal);
|
|
466
472
|
const logs = res.body;
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
473
|
+
if (logs.length === 0) {
|
|
474
|
+
return { items: [], next: null };
|
|
475
|
+
}
|
|
476
|
+
const nextFrom = this.logCheckpoint(logs[logs.length - 1]);
|
|
477
|
+
return { items: logs, next: nextFrom === from ? null : nextFrom };
|
|
478
|
+
}
|
|
479
|
+
async lastIngestedLogId(storage) {
|
|
480
|
+
const events = await storage.queryEvents({ name: LOGIN_EVENT });
|
|
481
|
+
let max = null;
|
|
482
|
+
for (const e of events) {
|
|
483
|
+
const logId = e.attributes.logId;
|
|
484
|
+
if (typeof logId === "string" && (max === null || logId > max)) {
|
|
485
|
+
max = logId;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return max;
|
|
470
489
|
}
|
|
471
490
|
async fetchDailyStats(page, options, signal) {
|
|
472
491
|
if (page !== null) {
|
|
@@ -500,12 +519,15 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
500
519
|
});
|
|
501
520
|
}
|
|
502
521
|
}
|
|
503
|
-
async writeLogs(storage, items) {
|
|
522
|
+
async writeLogs(storage, items, sinceMs) {
|
|
504
523
|
for (const log of items) {
|
|
505
524
|
const ts = parseEpoch(log.date, "iso");
|
|
506
525
|
if (ts === null) {
|
|
507
526
|
continue;
|
|
508
527
|
}
|
|
528
|
+
if (sinceMs !== null && ts < sinceMs) {
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
509
531
|
if (!isLogEventType(log.type)) {
|
|
510
532
|
continue;
|
|
511
533
|
}
|
|
@@ -514,7 +536,7 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
514
536
|
start_ts: ts,
|
|
515
537
|
end_ts: null,
|
|
516
538
|
attributes: {
|
|
517
|
-
logId: log
|
|
539
|
+
logId: this.logCheckpoint(log),
|
|
518
540
|
type: log.type,
|
|
519
541
|
userId: log.user_id ?? null,
|
|
520
542
|
ip: log.ip ?? null,
|
|
@@ -552,12 +574,12 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
552
574
|
await storage.metrics(samples, { names: [DAILY_METRIC] });
|
|
553
575
|
}
|
|
554
576
|
}
|
|
555
|
-
async writePhase(storage, phase, items) {
|
|
577
|
+
async writePhase(storage, phase, items, sinceMs) {
|
|
556
578
|
switch (phase) {
|
|
557
579
|
case "users":
|
|
558
580
|
return this.writeUsers(storage, items);
|
|
559
581
|
case "login_events":
|
|
560
|
-
return this.writeLogs(storage, items);
|
|
582
|
+
return this.writeLogs(storage, items, sinceMs);
|
|
561
583
|
case "daily_active_users":
|
|
562
584
|
return this.writeDailyStats(storage, items);
|
|
563
585
|
}
|
|
@@ -589,6 +611,8 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
589
611
|
PHASE_ORDER,
|
|
590
612
|
this.settings.resources
|
|
591
613
|
);
|
|
614
|
+
const sinceMs = options.since ? Date.parse(options.since) : null;
|
|
615
|
+
const logsSeed = !isFull && phases.includes("login_events") ? await this.lastIngestedLogId(storage) : null;
|
|
592
616
|
return paginateChunked({
|
|
593
617
|
phases,
|
|
594
618
|
cursor,
|
|
@@ -599,7 +623,7 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
599
623
|
case "users":
|
|
600
624
|
return this.fetchUsersPage(page, options, sig);
|
|
601
625
|
case "login_events":
|
|
602
|
-
return this.fetchLogsPage(page
|
|
626
|
+
return this.fetchLogsPage(page ?? logsSeed, sig);
|
|
603
627
|
case "daily_active_users":
|
|
604
628
|
return this.fetchDailyStats(page, options, sig);
|
|
605
629
|
}
|
|
@@ -608,7 +632,12 @@ var Auth0Connector = class _Auth0Connector extends BaseConnector {
|
|
|
608
632
|
if (page === null) {
|
|
609
633
|
await this.clearScopeOnFirstPage(storage, phase, isFull);
|
|
610
634
|
}
|
|
611
|
-
await this.writePhase(
|
|
635
|
+
await this.writePhase(
|
|
636
|
+
storage,
|
|
637
|
+
phase,
|
|
638
|
+
items,
|
|
639
|
+
phase === "login_events" ? sinceMs : null
|
|
640
|
+
);
|
|
612
641
|
}
|
|
613
642
|
});
|
|
614
643
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/auth0.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n standardRateLimitPolicy,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n domain: z\n .string()\n .min(1)\n .regex(\n /^[a-z0-9-]+(\\.[a-z0-9-]+)*\\.auth0\\.com$/i,\n 'Auth0 tenant domain, e.g. \"acme.us.auth0.com\" (no scheme).',\n )\n .meta({\n label: 'Tenant domain',\n description:\n 'Auth0 tenant domain (e.g. \"acme.us.auth0.com\" or a custom domain ending in .auth0.com). Used as the API host and as the audience when minting M2M tokens.',\n placeholder: 'acme.us.auth0.com',\n }),\n clientId: z.string().min(1).meta({\n label: 'M2M application client ID',\n description:\n 'Client ID of the Auth0 Machine-to-Machine application authorized to call the Management API.',\n placeholder: 'AbCdEf...',\n }),\n clientSecret: z.object({ $secret: z.string().min(1) }).meta({\n label: 'M2M application client secret',\n description:\n 'Client secret of the Auth0 Machine-to-Machine application. Stored as a secret.',\n placeholder: 'AUTH0_CLIENT_SECRET',\n secret: true,\n }),\n resources: z\n .array(z.enum(['users', 'login_events', 'daily_active_users']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which Auth0 resources to sync. Omit to sync all of them. The M2M application only needs the Management API scopes for the resources listed here (read:users, read:logs, read:stats).',\n }),\n statsLookbackDays: z.number().int().positive().max(30).optional().meta({\n label: 'Stats lookback (days)',\n description:\n 'How many days of daily-active-user / signup stats to refresh on each sync. Defaults to 30 (the maximum the Auth0 Daily Stats endpoint returns).',\n placeholder: '30',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Auth0',\n category: 'security',\n brandColor: '#EB5424',\n tagline:\n 'Sync users, login events, and daily active-user / signup metrics from an Auth0 tenant for identity, sign-up, and failed-login dashboards.',\n vendor: {\n name: 'Auth0',\n domain: 'auth0.com',\n apiDocs: 'https://auth0.com/docs/api/management/v2',\n website: 'https://auth0.com',\n },\n auth: {\n summary:\n 'OAuth 2.0 client-credentials flow against a Machine-to-Machine application authorized for the Auth0 Management API.',\n setup: [\n 'In the Auth0 Dashboard, open Applications -> Applications and create a new Machine to Machine Application.',\n 'Authorize the M2M app for the Auth0 Management API (Applications -> APIs -> Auth0 Management API -> Machine to Machine Applications).',\n 'Grant the M2M app the read:users, read:logs, and read:stats scopes (only the ones for the resources you intend to sync are required).',\n 'Copy the Domain (e.g. \"acme.us.auth0.com\"), Client ID, and Client Secret from the M2M application Settings tab.',\n 'Store the client secret as a rawdash secret and reference it from the connector config as `clientSecret: secret(\"AUTH0_CLIENT_SECRET\")`.',\n ],\n },\n rateLimit:\n 'Auth0 publishes X-RateLimit-Limit / X-RateLimit-Remaining / X-RateLimit-Reset response headers on Management API calls; the shared HTTP client backs off on 429 with the standard rate-limit policy.',\n limitations: [\n 'User enumeration uses offset pagination (page/per_page) and is capped at the first 1000 users per sync; tenants with more than 1000 users updated since the last run should increase sync frequency so each window stays under the cap.',\n 'Action / hook / branding configuration objects are out of scope.',\n 'Only Auth0 tenants on the *.auth0.com hostname suffix are supported; custom-domain tenants must still expose a *.auth0.com hostname for the Management API.',\n ],\n});\n\nexport type Auth0Resource = 'users' | 'login_events' | 'daily_active_users';\n\nexport interface Auth0Settings {\n domain: string;\n resources?: readonly Auth0Resource[];\n statsLookbackDays?: number;\n}\n\nconst auth0Credentials = {\n clientId: {\n description: 'Auth0 Machine-to-Machine application client ID',\n auth: 'required' as const,\n },\n clientSecret: {\n description: 'Auth0 Machine-to-Machine application client secret',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype Auth0Credentials = typeof auth0Credentials;\n\nconst auth0RateLimit = standardRateLimitPolicy({\n remainingHeader: 'x-ratelimit-remaining',\n resetHeader: 'x-ratelimit-reset',\n resetUnit: 's',\n});\n\nconst PHASE_ORDER = ['users', 'login_events', 'daily_active_users'] as const;\n\ntype Auth0Phase = (typeof PHASE_ORDER)[number];\n\ntype Auth0SyncCursor = ChunkedSyncCursor<Auth0Phase, string>;\n\nconst isAuth0SyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst USER_ENTITY = 'auth0_user';\nconst LOGIN_EVENT = 'auth0_login_event';\nconst DAILY_METRIC = 'auth0_daily_active_users';\n\nconst PAGE_SIZE = 100;\nconst MAX_USER_PAGES = 10;\nconst DEFAULT_STATS_LOOKBACK_DAYS = 30;\n\nconst LOG_EVENT_TYPES = ['s', 'f', 'seacft', 'fp'] as const;\ntype LogEventType = (typeof LOG_EVENT_TYPES)[number];\n\nconst idString = z.string().min(1);\n\nconst oauthTokenSchema = z.object({\n access_token: z.string().min(1),\n token_type: z.string().optional(),\n expires_in: z.number().optional(),\n});\n\nconst userIdentitySchema = z.object({\n connection: z.string().nullish(),\n provider: z.string().nullish(),\n user_id: z.union([z.string(), z.number()]).nullish(),\n isSocial: z.boolean().nullish(),\n});\n\nconst userSchema = z.object({\n user_id: idString,\n email: z.string().nullish(),\n email_verified: z.boolean().nullish(),\n identities: z.array(userIdentitySchema).nullish(),\n last_login: z.string().nullish(),\n logins_count: z.number().nullish(),\n created_at: z.string().nullish(),\n updated_at: z.string().nullish(),\n blocked: z.boolean().nullish(),\n});\n\nconst usersResponseSchema = z.object({\n start: z.number().optional(),\n limit: z.number().optional(),\n length: z.number().optional(),\n total: z.number().optional(),\n users: z.array(userSchema),\n});\n\nconst logSchema = z.object({\n _id: idString,\n log_id: z.string().nullish(),\n date: z.string(),\n type: z.string(),\n user_id: z.string().nullish(),\n user_name: z.string().nullish(),\n client_id: z.string().nullish(),\n ip: z.string().nullish(),\n connection: z.string().nullish(),\n strategy: z.string().nullish(),\n});\n\nconst logsResponseSchema = z.array(logSchema);\n\nconst dailyStatSchema = z.object({\n date: z.string(),\n logins: z.number().nullish(),\n signups: z.number().nullish(),\n leaked_passwords: z.number().nullish(),\n updated_at: z.string().nullish(),\n created_at: z.string().nullish(),\n});\n\nconst dailyStatsResponseSchema = z.array(dailyStatSchema);\n\nexport const auth0Resources = defineResources({\n [USER_ENTITY]: {\n shape: 'entity',\n filterable: [\n { field: 'blocked', ops: ['eq'], values: ['true', 'false'] },\n { field: 'identityProvider', ops: ['eq'] },\n ],\n description:\n 'Auth0 users keyed by user_id, with email, primary identity provider, last login, login count, and blocked flag.',\n endpoint: 'GET /api/v2/users',\n notes:\n 'Uses offset pagination (page / per_page) and is capped at the first 1000 users per sync. Incremental syncs filter on updated_at via the q parameter.',\n fields: [\n { name: 'email', description: 'Primary email address.' },\n {\n name: 'identityProvider',\n description:\n 'Provider of the primary identity (e.g. auth0, google-oauth2, samlp).',\n },\n {\n name: 'lastLogin',\n description: 'Most recent login timestamp (Unix ms).',\n },\n {\n name: 'loginsCount',\n description: 'Total successful logins (counter maintained by Auth0).',\n },\n {\n name: 'blocked',\n description: 'Whether the user has been administratively blocked.',\n },\n {\n name: 'createdAt',\n description: 'When the user record was created (Unix ms).',\n },\n ],\n responses: {\n oauth_token: oauthTokenSchema,\n users: usersResponseSchema,\n },\n },\n [LOGIN_EVENT]: {\n shape: 'event',\n filterable: [\n {\n field: 'type',\n ops: ['eq'],\n values: ['s', 'f', 'seacft', 'fp'],\n },\n ],\n description:\n 'Login / authentication events from the Auth0 Logs endpoint. One event per log row of type s (success), f (failure), seacft (token exchange success), or fp (failed change password).',\n endpoint: 'GET /api/v2/logs',\n notes:\n 'Uses offset pagination (page / per_page) and is capped at the first 1000 events per sync. Incremental syncs filter on date via the q parameter.',\n fields: [\n { name: 'logId', description: 'Auth0 log row id.' },\n {\n name: 'type',\n description: 'Auth0 log type (s, f, seacft, fp).',\n },\n {\n name: 'userId',\n description: 'Auth0 user_id the event belongs to (may be null).',\n },\n { name: 'ip', description: 'Source IP of the login attempt.' },\n {\n name: 'connection',\n description: 'Connection name used for the login.',\n },\n {\n name: 'strategy',\n description:\n 'Identity provider strategy (e.g. auth0, google-oauth2, samlp).',\n },\n ],\n responses: { logs: logsResponseSchema },\n },\n [DAILY_METRIC]: {\n shape: 'metric',\n description:\n 'Daily logins and signups, one sample per day for the configured lookback window (up to 30 days, the Daily Stats endpoint maximum).',\n endpoint: 'GET /api/v2/stats/daily',\n unit: 'count',\n granularity: '1d',\n dimensions: [\n {\n name: 'kind',\n description: 'Either \"logins\" or \"signups\".',\n },\n ],\n responses: { daily_stats: dailyStatsResponseSchema },\n },\n});\n\nexport const id = 'auth0';\n\ntype UsersResponse = z.infer<typeof usersResponseSchema>;\ntype LogsResponse = z.infer<typeof logsResponseSchema>;\ntype DailyStatsResponse = z.infer<typeof dailyStatsResponseSchema>;\ntype OauthTokenResponse = z.infer<typeof oauthTokenSchema>;\ntype Auth0User = z.infer<typeof userSchema>;\ntype Auth0Log = z.infer<typeof logSchema>;\ntype Auth0DailyStat = z.infer<typeof dailyStatSchema>;\n\nfunction escapeLuceneRange(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) {\n return iso;\n }\n return d.toISOString();\n}\n\nfunction isLogEventType(value: string): value is LogEventType {\n return (LOG_EVENT_TYPES as readonly string[]).includes(value);\n}\n\nfunction primaryIdentityProvider(user: Auth0User): string | null {\n const identities = user.identities ?? [];\n const first = identities[0];\n if (!first) {\n const id = user.user_id;\n const sep = id.indexOf('|');\n return sep > 0 ? id.slice(0, sep) : null;\n }\n return first.provider ?? null;\n}\n\nfunction yyyymmdd(date: Date): string {\n const y = date.getUTCFullYear();\n const m = String(date.getUTCMonth() + 1).padStart(2, '0');\n const d = String(date.getUTCDate()).padStart(2, '0');\n return `${y}${m}${d}`;\n}\n\nexport class Auth0Connector extends BaseConnector<\n Auth0Settings,\n Auth0Credentials\n> {\n static readonly id = id;\n\n static readonly resources = auth0Resources;\n\n static readonly schemas = schemasFromResources(auth0Resources);\n\n static create(input: unknown, ctx?: ConnectorContext): Auth0Connector {\n const parsed = configFields.parse(input);\n return new Auth0Connector(\n {\n domain: parsed.domain,\n resources: parsed.resources,\n statsLookbackDays: parsed.statsLookbackDays,\n },\n {\n clientId: parsed.clientId,\n clientSecret: parsed.clientSecret,\n },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = auth0Credentials;\n\n private accessToken: string | null = null;\n\n private baseUrl(): string {\n return `https://${this.settings.domain}`;\n }\n\n private audience(): string {\n return `https://${this.settings.domain}/api/v2/`;\n }\n\n private async refreshAccessToken(signal?: AbortSignal): Promise<string> {\n const res = await this.post<OauthTokenResponse>(\n `${this.baseUrl()}/oauth/token`,\n {\n resource: 'oauth_token',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('auth0'),\n },\n body: JSON.stringify({\n grant_type: 'client_credentials',\n client_id: this.creds.clientId,\n client_secret: this.creds.clientSecret,\n audience: this.audience(),\n }),\n signal,\n },\n );\n return res.body.access_token;\n }\n\n private async getAccessToken(signal?: AbortSignal): Promise<string> {\n if (!this.accessToken) {\n this.accessToken = await this.refreshAccessToken(signal);\n }\n return this.accessToken;\n }\n\n private async apiGet<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n ): Promise<HttpResponse<T>> {\n const token = await this.getAccessToken(signal);\n return this.get<T>(url, {\n resource,\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('auth0'),\n },\n rateLimit: auth0RateLimit,\n signal,\n });\n }\n\n private parsePageCursor(page: string | null): number {\n if (!page) {\n return 0;\n }\n const n = Number.parseInt(page, 10);\n if (!Number.isFinite(n) || n < 0) {\n return 0;\n }\n return n;\n }\n\n private buildUsersUrl(page: number, options: SyncOptions): string {\n const u = new URL(`${this.baseUrl()}/api/v2/users`);\n u.searchParams.set('page', String(page));\n u.searchParams.set('per_page', String(PAGE_SIZE));\n u.searchParams.set('include_totals', 'true');\n u.searchParams.set('sort', 'updated_at:1');\n if (options.since) {\n const iso = escapeLuceneRange(options.since);\n u.searchParams.set('q', `updated_at:[${iso} TO *]`);\n u.searchParams.set('search_engine', 'v3');\n }\n return u.toString();\n }\n\n private buildLogsUrl(page: number, options: SyncOptions): string {\n const u = new URL(`${this.baseUrl()}/api/v2/logs`);\n u.searchParams.set('page', String(page));\n u.searchParams.set('per_page', String(PAGE_SIZE));\n u.searchParams.set('include_totals', 'false');\n u.searchParams.set('sort', 'date:1');\n const typeClause = LOG_EVENT_TYPES.map((t) => `type:\"${t}\"`).join(' OR ');\n const clauses: string[] = [`(${typeClause})`];\n if (options.since) {\n clauses.push(`date:[${escapeLuceneRange(options.since)} TO *]`);\n }\n u.searchParams.set('q', clauses.join(' AND '));\n return u.toString();\n }\n\n private buildDailyStatsUrl(options: SyncOptions): string {\n const lookback =\n this.settings.statsLookbackDays ?? DEFAULT_STATS_LOOKBACK_DAYS;\n const to = new Date();\n let from = new Date(to.getTime() - (lookback - 1) * 24 * 60 * 60 * 1000);\n if (options.since) {\n const sinceMs = Date.parse(options.since);\n if (Number.isFinite(sinceMs)) {\n const sinceDate = new Date(sinceMs);\n if (sinceDate.getTime() > from.getTime()) {\n from = sinceDate;\n }\n }\n }\n const u = new URL(`${this.baseUrl()}/api/v2/stats/daily`);\n u.searchParams.set('from', yyyymmdd(from));\n u.searchParams.set('to', yyyymmdd(to));\n return u.toString();\n }\n\n private async fetchUsersPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: Auth0User[]; next: string | null }> {\n const pageNum = this.parsePageCursor(page);\n const url = this.buildUsersUrl(pageNum, options);\n const res = await this.apiGet<UsersResponse>(url, 'users', signal);\n const users = res.body.users;\n const length = res.body.length ?? users.length;\n const nextPage = pageNum + 1;\n const hasMore = length >= PAGE_SIZE && nextPage < MAX_USER_PAGES;\n return { items: users, next: hasMore ? String(nextPage) : null };\n }\n\n private async fetchLogsPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: Auth0Log[]; next: string | null }> {\n const pageNum = this.parsePageCursor(page);\n const url = this.buildLogsUrl(pageNum, options);\n const res = await this.apiGet<LogsResponse>(url, 'logs', signal);\n const logs = res.body;\n const nextPage = pageNum + 1;\n const hasMore = logs.length >= PAGE_SIZE && nextPage < MAX_USER_PAGES;\n return { items: logs, next: hasMore ? String(nextPage) : null };\n }\n\n private async fetchDailyStats(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: Auth0DailyStat[]; next: string | null }> {\n if (page !== null) {\n return { items: [], next: null };\n }\n const url = this.buildDailyStatsUrl(options);\n const res = await this.apiGet<DailyStatsResponse>(\n url,\n 'daily_stats',\n signal,\n );\n return { items: res.body, next: null };\n }\n\n private async writeUsers(\n storage: StorageHandle,\n items: Auth0User[],\n ): Promise<void> {\n for (const u of items) {\n const lastLoginMs = parseEpoch(u.last_login ?? null, 'iso');\n const createdMs = parseEpoch(u.created_at ?? null, 'iso');\n const updatedMs = parseEpoch(u.updated_at ?? null, 'iso');\n await storage.entity({\n type: USER_ENTITY,\n id: u.user_id,\n attributes: {\n email: u.email ?? null,\n identityProvider: primaryIdentityProvider(u),\n lastLogin: lastLoginMs,\n loginsCount: u.logins_count ?? null,\n blocked: u.blocked ?? false,\n createdAt: createdMs,\n },\n updated_at: updatedMs ?? createdMs ?? 0,\n });\n }\n }\n\n private async writeLogs(\n storage: StorageHandle,\n items: Auth0Log[],\n ): Promise<void> {\n for (const log of items) {\n const ts = parseEpoch(log.date, 'iso');\n if (ts === null) {\n continue;\n }\n if (!isLogEventType(log.type)) {\n continue;\n }\n await storage.event({\n name: LOGIN_EVENT,\n start_ts: ts,\n end_ts: null,\n attributes: {\n logId: log._id,\n type: log.type,\n userId: log.user_id ?? null,\n ip: log.ip ?? null,\n connection: log.connection ?? null,\n strategy: log.strategy ?? null,\n },\n });\n }\n }\n\n private async writeDailyStats(\n storage: StorageHandle,\n items: Auth0DailyStat[],\n ): Promise<void> {\n const samples: Array<{\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number>;\n }> = [];\n for (const stat of items) {\n const ts = parseEpoch(stat.date, 'iso');\n if (ts === null) {\n continue;\n }\n if (typeof stat.logins === 'number' && Number.isFinite(stat.logins)) {\n samples.push({\n name: DAILY_METRIC,\n ts,\n value: stat.logins,\n attributes: { kind: 'logins' },\n });\n }\n if (typeof stat.signups === 'number' && Number.isFinite(stat.signups)) {\n samples.push({\n name: DAILY_METRIC,\n ts,\n value: stat.signups,\n attributes: { kind: 'signups' },\n });\n }\n }\n if (samples.length > 0) {\n await storage.metrics(samples, { names: [DAILY_METRIC] });\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: Auth0Phase,\n items: unknown[],\n ): Promise<void> {\n switch (phase) {\n case 'users':\n return this.writeUsers(storage, items as Auth0User[]);\n case 'login_events':\n return this.writeLogs(storage, items as Auth0Log[]);\n case 'daily_active_users':\n return this.writeDailyStats(storage, items as Auth0DailyStat[]);\n }\n }\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: Auth0Phase,\n isFull: boolean,\n ): Promise<void> {\n if (!isFull) {\n return;\n }\n switch (phase) {\n case 'users':\n await storage.entities([], { types: [USER_ENTITY] });\n return;\n case 'login_events':\n await storage.events([], { names: [LOGIN_EVENT] });\n return;\n case 'daily_active_users':\n await storage.metrics([], { names: [DAILY_METRIC] });\n return;\n }\n }\n\n private resolveCursor(cursor: unknown): Auth0SyncCursor | undefined {\n return isAuth0SyncCursor(cursor) ? cursor : undefined;\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n\n const phases = selectActivePhases<Auth0Resource, Auth0Phase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n return paginateChunked<Auth0Phase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'users':\n return this.fetchUsersPage(page, options, sig);\n case 'login_events':\n return this.fetchLogsPage(page, options, sig);\n case 'daily_active_users':\n return this.fetchDailyStats(page, options, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(storage, phase, isFull);\n }\n await this.writePhase(storage, phase, items);\n },\n });\n }\n}\n","import { Auth0Connector } from './auth0';\n\nexport {\n Auth0Connector,\n auth0Resources as resources,\n configFields,\n doc,\n id,\n} from './auth0';\nexport type { Auth0Resource, Auth0Settings } from './auth0';\nexport default Auth0Connector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,IAAI,mBAAmB;AAChE;AEUO,SAAS,wBACd,QACiB;AACjB,QAAM,EAAE,iBAAiB,aAAa,WAAW,gBAAgB,IAAI;AACrE,QAAM,aAAa,cAAc,MAAM,MAAO;AAC9C,SAAO;IACL,MAAM,GAAG;AACP,YAAM,eAAe,EAAE,IAAI,eAAe;AAC1C,UAAI,iBAAiB,QAAQ,aAAa,KAAK,MAAM,IAAI;AACvD,eAAO;MACT;AACA,YAAM,YAAY,OAAO,YAAY;AACrC,UAAI,CAAC,OAAO,SAAS,SAAS,GAAG;AAC/B,eAAO;MACT;AACA,YAAM,WAAW,EAAE,IAAI,WAAW;AAClC,UAAI,aAAa,MAAM;AACrB,YAAI,oBAAoB,QAAW;AACjC,iBAAO;QACT;AACA,eAAO;UACL;UACA,SAAS,IAAI,KAAK,KAAK,IAAI,IAAI,eAAe;QAChD;MACF;AACA,UAAI,SAAS,KAAK,MAAM,IAAI;AAC1B,eAAO;MACT;AACA,YAAM,QAAQ,OAAO,QAAQ;AAC7B,UAAI,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAAG;AACxC,eAAO;MACT;AACA,YAAM,UAAU,QAAQ;AACxB,UAAI,CAAC,OAAO,SAAS,OAAO,GAAG;AAC7B,eAAO;MACT;AACA,aAAO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AA,MACF,KAAK;AACH,cAAM,QAAQ,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC,YAAY,EAAE,CAAC;AACnD;AAAA,IACJ;AAAA,EACF;AAAA,EAEQ,cAAc,QAA8C;AAClE,WAAO,kBAAkB,MAAM,IAAI,SAAS;AAAA,EAC9C;AAAA,EAEA,MAAM,KACJ,SACA,SACA,QACqB;AACrB,UAAM,SAAS,KAAK,cAAc,QAAQ,MAAM;AAChD,UAAM,SAAS,QAAQ,SAAS;AAEhC,UAAM,SAAS;AAAA,MACb,CAAC,MAAM;AAAA,MACP;AAAA,MACA,KAAK,SAAS;AAAA,IAChB;AAEA,WAAO,gBAAoC;AAAA,MACzC;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ,KAAK;AAAA,MACb,WAAW,OAAO,OAAO,MAAM,QAAQ;AACrC,gBAAQ,OAAO;AAAA,UACb,KAAK;AACH,mBAAO,KAAK,eAAe,MAAM,SAAS,GAAG;AAAA,UAC/C,KAAK;AACH,mBAAO,KAAK,cAAc,MAAM,SAAS,GAAG;AAAA,UAC9C,KAAK;AACH,mBAAO,KAAK,gBAAgB,MAAM,SAAS,GAAG;AAAA,QAClD;AAAA,MACF;AAAA,MACA,YAAY,OAAO,OAAO,OAAO,SAAS;AACxC,YAAI,SAAS,MAAM;AACjB,gBAAM,KAAK,sBAAsB,SAAS,OAAO,MAAM;AAAA,QACzD;AACA,cAAM,KAAK,WAAW,SAAS,OAAO,KAAK;AAAA,MAC7C;AAAA,IACF,CAAC;AAAA,EACH;AACF;;;ACrrBA,IAAO,gBAAQ;","names":["id"]}
|
|
1
|
+
{"version":3,"sources":["../../../connector-shared/src/errors.ts","../../../connector-shared/src/retry.ts","../../../connector-shared/src/version.ts","../../../connector-shared/src/request.ts","../../../connector-shared/src/rate-limit.ts","../../../connector-shared/src/map-concurrent.ts","../../../connector-shared/src/sanitize.ts","../../../connector-shared/src/epoch.ts","../../../connector-shared/src/pagination.ts","../../../connector-shared/src/logger.ts","../src/auth0.ts","../src/index.ts"],"sourcesContent":["import type { HttpResponse } from './types';\n\nexport type HttpErrorKind =\n | 'transient'\n | 'rate_limit'\n | 'auth'\n | 'upstream_bug'\n | 'client_bug';\n\nexport abstract class HttpClientError extends Error {\n abstract readonly kind: HttpErrorKind;\n readonly response?: HttpResponse;\n\n constructor(message: string, response?: HttpResponse) {\n super(message);\n this.name = new.target.name;\n this.response = response;\n }\n}\n\nexport class TransientError extends HttpClientError {\n readonly kind = 'transient' as const;\n}\n\nexport class RateLimitError extends HttpClientError {\n readonly kind = 'rate_limit' as const;\n readonly retryAfter?: Date;\n\n constructor(message: string, response?: HttpResponse, retryAfter?: Date) {\n super(message, response);\n this.retryAfter = retryAfter;\n }\n}\n\nexport class AuthError extends HttpClientError {\n readonly kind = 'auth' as const;\n}\n\nexport class UpstreamBugError extends HttpClientError {\n readonly kind = 'upstream_bug' as const;\n}\n\nexport class ClientBugError extends HttpClientError {\n readonly kind = 'client_bug' as const;\n}\n\nexport function classifyStatus(status: number): HttpErrorKind {\n if (status === 429) {\n return 'rate_limit';\n }\n if (status === 401 || status === 403) {\n return 'auth';\n }\n if (status === 408) {\n return 'transient';\n }\n if (status >= 500) {\n return 'upstream_bug';\n }\n if (status >= 400) {\n return 'client_bug';\n }\n return 'client_bug';\n}\n\nexport function errorForStatus(\n message: string,\n response: HttpResponse,\n retryAfter?: Date,\n): HttpClientError {\n const kind = classifyStatus(response.status);\n switch (kind) {\n case 'rate_limit':\n return new RateLimitError(message, response, retryAfter);\n case 'auth':\n return new AuthError(message, response);\n case 'transient':\n return new TransientError(message, response);\n case 'upstream_bug':\n return new UpstreamBugError(message, response);\n case 'client_bug':\n return new ClientBugError(message, response);\n }\n}\n","import { HttpClientError, RateLimitError, TransientError } from './errors';\n\nexport interface RetryPolicy {\n maxAttempts?: number;\n initialDelayMs?: number;\n maxDelayMs?: number;\n retryOn?: (status: number | null, err?: Error) => boolean;\n}\n\nexport const defaultRetryOn = (status: number | null, err?: Error): boolean => {\n if (err instanceof RateLimitError) {\n return true;\n }\n if (err instanceof TransientError) {\n return true;\n }\n if (status === null) {\n return err instanceof Error && !(err instanceof HttpClientError);\n }\n if (status === 408 || status === 429) {\n return true;\n }\n if (status >= 500) {\n return true;\n }\n return false;\n};\n\nexport function backoffDelayMs(\n attempt: number,\n policy: Required<Pick<RetryPolicy, 'initialDelayMs' | 'maxDelayMs'>>,\n): number {\n const base = policy.initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, policy.maxDelayMs);\n}\n\nexport function parseRetryAfter(\n headerValue: string | null,\n now: Date = new Date(),\n): Date | undefined {\n if (!headerValue) {\n return undefined;\n }\n const trimmed = headerValue.trim();\n if (/^\\d+$/.test(trimmed)) {\n return new Date(now.getTime() + Number(trimmed) * 1000);\n }\n const parsed = Date.parse(trimmed);\n if (Number.isNaN(parsed)) {\n return undefined;\n }\n return new Date(parsed);\n}\n\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.reject(signal.reason ?? new Error('Aborted'));\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal!.reason ?? new Error('Aborted'));\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n","export const HTTP_CLIENT_VERSION = '0.0.0';\n\nexport const DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n\nexport function connectorUserAgent(connectorId: string): string {\n return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;\n}\n","import {\n AuthError,\n ClientBugError,\n HttpClientError,\n RateLimitError,\n TransientError,\n UpstreamBugError,\n errorForStatus,\n} from './errors';\nimport { defaultRetryOn, parseRetryAfter, sleep } from './retry';\nimport type { FetchLike, HttpMethod, HttpRequest, HttpResponse } from './types';\nimport { DEFAULT_USER_AGENT } from './version';\n\nconst DEFAULT_TIMEOUT_MS = 10_000;\nconst DEFAULT_MAX_ATTEMPTS = 3;\nconst DEFAULT_INITIAL_DELAY_MS = 1000;\nconst DEFAULT_MAX_DELAY_MS = 60_000;\nconst OBSERVER_TIMEOUT_MS = 250;\n\nexport interface RequestObservation {\n url: string;\n method: HttpMethod;\n status: number;\n resource: string;\n requestId: string;\n body: unknown;\n}\n\nexport type RequestObserver = (\n event: RequestObservation,\n) => void | Promise<void>;\n\nexport interface RequestOptions {\n fetch?: FetchLike;\n observer?: RequestObserver;\n resource: string;\n requestId?: string;\n}\n\nasync function notifyObserver(\n observer: RequestObserver,\n event: RequestObservation,\n): Promise<void> {\n let result: void | Promise<void>;\n try {\n result = observer(event);\n } catch (err) {\n console.warn('[connector-shared] request observer threw:', err);\n return;\n }\n if (!(result instanceof Promise)) {\n return;\n }\n const guarded = result.catch((err) => {\n console.warn('[connector-shared] request observer rejected:', err);\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, OBSERVER_TIMEOUT_MS);\n });\n try {\n await Promise.race([guarded, timeout]);\n } finally {\n if (timer) {\n clearTimeout(timer);\n }\n }\n}\n\nfunction newRequestId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) {\n return c.randomUUID();\n }\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction mergeHeaders(\n defaults: Record<string, string>,\n overrides: Record<string, string> | undefined,\n): Record<string, string> {\n const merged: Record<string, string> = {};\n for (const [k, v] of Object.entries(defaults)) {\n merged[k.toLowerCase()] = v;\n }\n if (overrides) {\n for (const [k, v] of Object.entries(overrides)) {\n merged[k.toLowerCase()] = v;\n }\n }\n return merged;\n}\n\nfunction linkTimeoutSignal(\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): { signal: AbortSignal; cancel: () => void } {\n const controller = new AbortController();\n const onParentAbort = () => {\n controller.abort(parent?.reason);\n };\n if (parent) {\n if (parent.aborted) {\n controller.abort(parent.reason);\n } else {\n parent.addEventListener('abort', onParentAbort, { once: true });\n }\n }\n const timer = setTimeout(() => {\n controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n return {\n signal: controller.signal,\n cancel: () => {\n clearTimeout(timer);\n if (parent) {\n parent.removeEventListener('abort', onParentAbort);\n }\n },\n };\n}\n\nasync function readBody(res: Response, parseJson: boolean): Promise<unknown> {\n if (res.status === 204 || res.status === 205) {\n return null;\n }\n const contentType = res.headers.get('content-type') ?? '';\n if (parseJson && contentType.includes('application/json')) {\n const text = await res.text();\n if (text.length === 0) {\n return null;\n }\n return JSON.parse(text);\n }\n return res.text();\n}\n\nexport async function request<T = unknown>(\n req: HttpRequest,\n options: RequestOptions,\n): Promise<HttpResponse<T>> {\n const fetchImpl: FetchLike = options.fetch ?? (globalThis.fetch as FetchLike);\n const retry = req.retry ?? {};\n const maxAttempts = retry.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n const initialDelayMs = retry.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;\n const maxDelayMs = retry.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;\n const retryOn = retry.retryOn ?? defaultRetryOn;\n const timeoutMs = req.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const parseJson = req.parseJson ?? true;\n\n const headers = mergeHeaders(\n {\n 'User-Agent': DEFAULT_USER_AGENT,\n Accept: 'application/json',\n },\n req.headers,\n );\n\n let lastErr: Error | undefined;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n req.signal?.throwIfAborted();\n\n const { signal, cancel } = linkTimeoutSignal(req.signal, timeoutMs);\n let res: Response;\n try {\n res = await fetchImpl(req.url, {\n method: req.method ?? 'GET',\n headers,\n body: req.body as RequestInit['body'],\n signal,\n });\n } catch (err) {\n cancel();\n if (req.signal?.aborted) {\n throw req.signal.reason ?? err;\n }\n const error = err instanceof Error ? err : new Error(String(err));\n lastErr = error;\n if (attempt < maxAttempts - 1 && retryOn(null, error)) {\n const delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n await sleep(delay, req.signal);\n continue;\n }\n throw new TransientError(error.message);\n }\n cancel();\n\n const body = await readBody(res, parseJson);\n const httpResponse: HttpResponse<T> = {\n status: res.status,\n headers: res.headers,\n body: body as T,\n };\n if (req.rateLimit) {\n const state = req.rateLimit.parse(res.headers);\n if (state) {\n httpResponse.rateLimitState = state;\n }\n }\n\n if (options.observer) {\n await notifyObserver(options.observer, {\n url: req.url,\n method: req.method ?? 'GET',\n status: res.status,\n resource: options.resource,\n requestId: options.requestId ?? newRequestId(),\n body,\n });\n }\n\n if (res.ok) {\n return httpResponse;\n }\n\n const retryAfter = parseRetryAfter(res.headers.get('retry-after'));\n const message = `HTTP ${res.status} ${res.statusText} for ${req.method ?? 'GET'} ${req.url}`;\n const err = errorForStatus(message, httpResponse, retryAfter);\n\n if (\n attempt < maxAttempts - 1 &&\n retryOn(res.status, err) &&\n !(err instanceof AuthError) &&\n !(err instanceof ClientBugError)\n ) {\n lastErr = err;\n let delay = computeDelay(attempt, initialDelayMs, maxDelayMs);\n if (err instanceof RateLimitError && retryAfter) {\n const wait = retryAfter.getTime() - Date.now();\n if (wait > 0) {\n delay = Math.min(wait, maxDelayMs);\n }\n }\n await sleep(delay, req.signal);\n continue;\n }\n\n throw err;\n }\n\n throw lastErr ?? new UpstreamBugError('Exhausted retry attempts');\n}\n\nfunction computeDelay(\n attempt: number,\n initialDelayMs: number,\n maxDelayMs: number,\n): number {\n const base = initialDelayMs * 2 ** attempt;\n const jitter = base * 0.25 * Math.random();\n return Math.min(base + jitter, maxDelayMs);\n}\n\nexport { HttpClientError };\n","export interface RateLimitState {\n remaining: number;\n resetAt: Date;\n}\n\nexport interface RateLimitPolicy {\n parse(headers: Headers): RateLimitState | null;\n}\n\nexport interface StandardRateLimitPolicyConfig {\n remainingHeader: string;\n resetHeader: string;\n resetUnit: 's' | 'ms';\n resetFallbackMs?: number;\n}\n\nexport function standardRateLimitPolicy(\n config: StandardRateLimitPolicyConfig,\n): RateLimitPolicy {\n const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;\n const multiplier = resetUnit === 's' ? 1000 : 1;\n return {\n parse(h) {\n const remainingRaw = h.get(remainingHeader);\n if (remainingRaw === null || remainingRaw.trim() === '') {\n return null;\n }\n const remaining = Number(remainingRaw);\n if (!Number.isFinite(remaining)) {\n return null;\n }\n const resetRaw = h.get(resetHeader);\n if (resetRaw === null) {\n if (resetFallbackMs === undefined) {\n return null;\n }\n return {\n remaining,\n resetAt: new Date(Date.now() + resetFallbackMs),\n };\n }\n if (resetRaw.trim() === '') {\n return null;\n }\n const reset = Number(resetRaw);\n if (!Number.isFinite(reset) || reset < 0) {\n return null;\n }\n const resetMs = reset * multiplier;\n if (!Number.isFinite(resetMs)) {\n return null;\n }\n return { remaining, resetAt: new Date(resetMs) };\n },\n };\n}\n","export async function mapWithConcurrency<T, R>(\n items: readonly T[],\n concurrency: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n if (items.length === 0) {\n return results;\n }\n const normalized = Number.isFinite(concurrency) ? Math.floor(concurrency) : 1;\n const limit = Math.max(1, Math.min(normalized, items.length));\n let next = 0;\n let failed = false;\n\n async function worker(): Promise<void> {\n while (!failed) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n try {\n results[i] = await fn(items[i]!, i);\n } catch (err) {\n failed = true;\n throw err;\n }\n }\n }\n\n const workers: Promise<void>[] = [];\n for (let w = 0; w < limit; w++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n return results;\n}\n","export interface SanitizeAllowedUrlOptions {\n url: string | null;\n host: string;\n pathname: string;\n protocol?: 'https:' | 'http:';\n}\n\nexport function sanitizeAllowedUrl(\n options: SanitizeAllowedUrlOptions,\n): string | null {\n const { url, host, pathname, protocol = 'https:' } = options;\n if (url === null) {\n return null;\n }\n try {\n const u = new URL(url);\n if (u.protocol !== protocol || u.host !== host || u.pathname !== pathname) {\n return null;\n }\n return u.toString();\n } catch {\n return null;\n }\n}\n","export type EpochUnit = 'ms' | 's' | 'iso';\n\nexport function parseEpoch(\n value: number | string | null | undefined,\n unit: EpochUnit,\n): number | null {\n if (value === null || value === undefined) {\n return null;\n }\n if (unit === 'iso') {\n if (typeof value !== 'string') {\n return null;\n }\n const ms = new Date(value).getTime();\n return Number.isFinite(ms) ? ms : null;\n }\n if (typeof value === 'string' && value.trim() === '') {\n return null;\n }\n const n = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(n)) {\n return null;\n }\n const result = unit === 's' ? n * 1000 : n;\n return Number.isFinite(result) ? result : null;\n}\n","import { request } from './request';\nimport type { HttpRequest } from './types';\n\nexport function parseLinkHeader(header: string | null): Record<string, string> {\n if (!header) {\n return {};\n }\n const result: Record<string, string> = {};\n for (const part of header.split(',')) {\n const match = part.match(/<([^>]+)>\\s*;\\s*rel=\"([^\"]+)\"/);\n if (match) {\n result[match[2]!] = match[1]!;\n }\n }\n return result;\n}\n\nexport async function* paginateLink<T>(\n initial: HttpRequest,\n parse: (body: unknown) => T[],\n options: { resource: string },\n): AsyncIterable<T> {\n let next: string | null = initial.url;\n while (next) {\n const res: Awaited<ReturnType<typeof request>> = await request(\n {\n ...initial,\n url: next,\n },\n { resource: options.resource },\n );\n for (const item of parse(res.body)) {\n yield item;\n }\n const links = parseLinkHeader(res.headers.get('link'));\n next = links['next'] ?? null;\n }\n}\n\nexport async function* paginateCursor<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; nextCursor: string | null },\n buildNext: (req: HttpRequest, cursor: string) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let req: HttpRequest = initial;\n while (true) {\n const res = await request(req, { resource: options.resource });\n const { items, nextCursor } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!nextCursor) {\n return;\n }\n req = buildNext(req, nextCursor);\n }\n}\n\nexport async function* paginatePage<T>(\n initial: HttpRequest,\n parse: (body: unknown) => { items: T[]; hasMore: boolean },\n buildPage: (req: HttpRequest, page: number) => HttpRequest,\n options: { resource: string },\n): AsyncIterable<T> {\n let page = 1;\n while (true) {\n const req = page === 1 ? initial : buildPage(initial, page);\n const res = await request(req, { resource: options.resource });\n const { items, hasMore } = parse(res.body);\n for (const item of items) {\n yield item;\n }\n if (!hasMore || items.length === 0) {\n return;\n }\n page++;\n }\n}\n","export type LogFields = Record<string, unknown>;\n\nexport interface ConnectorLogger {\n info(event: string, fields?: LogFields): void;\n warn(event: string, fields?: LogFields): void;\n}\n\nexport interface ConnectorLoggerOptions {\n scope: string;\n}\n\nconst MAX_VALUE_LEN = 120;\n\nfunction truncate(s: string, max = MAX_VALUE_LEN): string {\n if (s.length <= max) {\n return s;\n }\n return `${s.slice(0, max - 1)}…`;\n}\n\nfunction formatValue(value: unknown): string {\n if (value === null) {\n return 'null';\n }\n if (value === undefined) {\n return '';\n }\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n if (typeof value === 'string') {\n const t = truncate(value);\n if (/[\\s\"=]/.test(t)) {\n return JSON.stringify(t);\n }\n return t;\n }\n if (typeof value === 'bigint') {\n return value.toString();\n }\n let json: string | undefined;\n try {\n json = JSON.stringify(value);\n } catch {\n json = undefined;\n }\n return truncate(json ?? String(value));\n}\n\nexport function formatLogFields(fields?: LogFields): string {\n if (!fields) {\n return '';\n }\n const parts: string[] = [];\n for (const [k, v] of Object.entries(fields)) {\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${formatValue(v)}`);\n }\n return parts.length > 0 ? ` ${parts.join(' ')}` : '';\n}\n\nexport function formatLogLine(\n scope: string,\n event: string,\n fields?: LogFields,\n): string {\n return `[${scope}] ${event}${formatLogFields(fields)}`;\n}\n\nexport function createDefaultConnectorLogger(\n opts: ConnectorLoggerOptions,\n): ConnectorLogger {\n return {\n info(event, fields) {\n console.info(formatLogLine(opts.scope, event, fields));\n },\n warn(event, fields) {\n console.warn(formatLogLine(opts.scope, event, fields));\n },\n };\n}\n\nconst NOOP_LOGGER: ConnectorLogger = {\n info() {},\n warn() {},\n};\n\nexport function noopConnectorLogger(): ConnectorLogger {\n return NOOP_LOGGER;\n}\n","import {\n type HttpResponse,\n connectorUserAgent,\n parseEpoch,\n standardRateLimitPolicy,\n} from '@rawdash/connector-shared';\nimport {\n BaseConnector,\n type ChunkedSyncCursor,\n type ConnectorContext,\n type ConnectorDoc,\n type CredentialsSchema,\n type StorageHandle,\n type SyncOptions,\n type SyncResult,\n defineConfigFields,\n defineConnectorDoc,\n defineResources,\n makeChunkedCursorGuard,\n paginateChunked,\n schemasFromResources,\n selectActivePhases,\n} from '@rawdash/core';\nimport { z } from 'zod';\n\nexport const configFields = defineConfigFields(\n z.object({\n domain: z\n .string()\n .min(1)\n .regex(\n /^[a-z0-9-]+(\\.[a-z0-9-]+)*\\.auth0\\.com$/i,\n 'Auth0 tenant domain, e.g. \"acme.us.auth0.com\" (no scheme).',\n )\n .meta({\n label: 'Tenant domain',\n description:\n 'Auth0 tenant domain (e.g. \"acme.us.auth0.com\" or a custom domain ending in .auth0.com). Used as the API host and as the audience when minting M2M tokens.',\n placeholder: 'acme.us.auth0.com',\n }),\n clientId: z.string().min(1).meta({\n label: 'M2M application client ID',\n description:\n 'Client ID of the Auth0 Machine-to-Machine application authorized to call the Management API.',\n placeholder: 'AbCdEf...',\n }),\n clientSecret: z.object({ $secret: z.string().min(1) }).meta({\n label: 'M2M application client secret',\n description:\n 'Client secret of the Auth0 Machine-to-Machine application. Stored as a secret.',\n placeholder: 'AUTH0_CLIENT_SECRET',\n secret: true,\n }),\n resources: z\n .array(z.enum(['users', 'login_events', 'daily_active_users']))\n .nonempty()\n .optional()\n .meta({\n label: 'Resources',\n description:\n 'Which Auth0 resources to sync. Omit to sync all of them. The M2M application only needs the Management API scopes for the resources listed here (read:users, read:logs, read:stats).',\n }),\n statsLookbackDays: z.number().int().positive().optional().meta({\n label: 'Stats lookback (days)',\n description:\n 'How many days of daily logins / signups stats to refresh on each sync. Defaults to 30; the Auth0 Daily Stats endpoint accepts an arbitrary from/to range.',\n placeholder: '30',\n }),\n }),\n);\n\nexport const doc: ConnectorDoc = defineConnectorDoc({\n displayName: 'Auth0',\n category: 'security',\n brandColor: '#EB5424',\n tagline:\n 'Sync users, login events, and daily login / signup metrics from an Auth0 tenant for identity, sign-up, and failed-login dashboards.',\n vendor: {\n name: 'Auth0',\n domain: 'auth0.com',\n apiDocs: 'https://auth0.com/docs/api/management/v2',\n website: 'https://auth0.com',\n },\n auth: {\n summary:\n 'OAuth 2.0 client-credentials flow against a Machine-to-Machine application authorized for the Auth0 Management API.',\n setup: [\n 'In the Auth0 Dashboard, open Applications -> Applications and create a new Machine to Machine Application.',\n 'Authorize the M2M app for the Auth0 Management API (Applications -> APIs -> Auth0 Management API -> Machine to Machine Applications).',\n 'Grant the M2M app the read:users, read:logs, and read:stats scopes (only the ones for the resources you intend to sync are required).',\n 'Copy the Domain (e.g. \"acme.us.auth0.com\"), Client ID, and Client Secret from the M2M application Settings tab.',\n 'Store the client secret as a rawdash secret and reference it from the connector config as `clientSecret: secret(\"AUTH0_CLIENT_SECRET\")`.',\n ],\n },\n rateLimit:\n 'Auth0 publishes X-RateLimit-Limit / X-RateLimit-Remaining / X-RateLimit-Reset response headers on Management API calls; the shared HTTP client backs off on 429 with the standard rate-limit policy.',\n limitations: [\n 'User enumeration uses offset pagination (page/per_page) and is capped at the first 1000 users per sync; tenants with more than 1000 users updated since the last run should increase sync frequency so each window stays under the cap.',\n 'Action / hook / branding configuration objects are out of scope.',\n 'Only Auth0 tenants on the `*.auth0.com` hostname suffix are supported; custom-domain tenants must still expose a `*.auth0.com` hostname for the Management API.',\n ],\n});\n\nexport type Auth0Resource = 'users' | 'login_events' | 'daily_active_users';\n\nexport interface Auth0Settings {\n domain: string;\n resources?: readonly Auth0Resource[];\n statsLookbackDays?: number;\n}\n\nconst auth0Credentials = {\n clientId: {\n description: 'Auth0 Machine-to-Machine application client ID',\n auth: 'required' as const,\n },\n clientSecret: {\n description: 'Auth0 Machine-to-Machine application client secret',\n auth: 'required' as const,\n },\n} satisfies CredentialsSchema;\n\ntype Auth0Credentials = typeof auth0Credentials;\n\nconst auth0RateLimit = standardRateLimitPolicy({\n remainingHeader: 'x-ratelimit-remaining',\n resetHeader: 'x-ratelimit-reset',\n resetUnit: 's',\n});\n\nconst PHASE_ORDER = ['users', 'login_events', 'daily_active_users'] as const;\n\ntype Auth0Phase = (typeof PHASE_ORDER)[number];\n\ntype Auth0SyncCursor = ChunkedSyncCursor<Auth0Phase, string>;\n\nconst isAuth0SyncCursor = makeChunkedCursorGuard(PHASE_ORDER);\n\nconst USER_ENTITY = 'auth0_user';\nconst LOGIN_EVENT = 'auth0_login_event';\nconst DAILY_METRIC = 'auth0_daily_active_users';\n\nconst PAGE_SIZE = 100;\nconst MAX_USER_PAGES = 10;\nconst DEFAULT_STATS_LOOKBACK_DAYS = 30;\n\nconst LOG_EVENT_TYPES = ['s', 'f', 'seacft', 'fp'] as const;\ntype LogEventType = (typeof LOG_EVENT_TYPES)[number];\n\nconst idString = z.string().min(1);\n\nconst oauthTokenSchema = z.object({\n access_token: z.string().min(1),\n token_type: z.string().optional(),\n expires_in: z.number().optional(),\n});\n\nconst userIdentitySchema = z.object({\n connection: z.string().nullish(),\n provider: z.string().nullish(),\n user_id: z.union([z.string(), z.number()]).nullish(),\n isSocial: z.boolean().nullish(),\n});\n\nconst userSchema = z.object({\n user_id: idString,\n email: z.string().nullish(),\n email_verified: z.boolean().nullish(),\n identities: z.array(userIdentitySchema).nullish(),\n last_login: z.string().nullish(),\n logins_count: z.number().nullish(),\n created_at: z.string().nullish(),\n updated_at: z.string().nullish(),\n blocked: z.boolean().nullish(),\n});\n\nconst usersResponseSchema = z.object({\n start: z.number().optional(),\n limit: z.number().optional(),\n length: z.number().optional(),\n total: z.number().optional(),\n users: z.array(userSchema),\n});\n\nconst logSchema = z.object({\n _id: idString,\n log_id: z.string().nullish(),\n date: z.string(),\n type: z.string(),\n user_id: z.string().nullish(),\n user_name: z.string().nullish(),\n client_id: z.string().nullish(),\n ip: z.string().nullish(),\n connection: z.string().nullish(),\n strategy: z.string().nullish(),\n});\n\nconst logsResponseSchema = z.array(logSchema);\n\nconst dailyStatSchema = z.object({\n date: z.string(),\n logins: z.number().nullish(),\n signups: z.number().nullish(),\n updated_at: z.string().nullish(),\n created_at: z.string().nullish(),\n});\n\nconst dailyStatsResponseSchema = z.array(dailyStatSchema);\n\nexport const auth0Resources = defineResources({\n [USER_ENTITY]: {\n shape: 'entity',\n filterable: [\n { field: 'blocked', ops: ['eq'], values: ['true', 'false'] },\n { field: 'identityProvider', ops: ['eq'] },\n ],\n description:\n 'Auth0 users keyed by user_id, with email, primary identity provider, last login, login count, and blocked flag.',\n endpoint: 'GET /api/v2/users',\n notes:\n 'Uses offset pagination (page / per_page) and is capped at the first 1000 users per sync. Incremental syncs filter on updated_at via the q parameter.',\n fields: [\n { name: 'email', description: 'Primary email address.' },\n {\n name: 'identityProvider',\n description:\n 'Provider of the primary identity (e.g. auth0, google-oauth2, samlp).',\n },\n {\n name: 'lastLogin',\n description: 'Most recent login timestamp (Unix ms).',\n },\n {\n name: 'loginsCount',\n description: 'Total successful logins (counter maintained by Auth0).',\n },\n {\n name: 'blocked',\n description: 'Whether the user has been administratively blocked.',\n },\n {\n name: 'createdAt',\n description: 'When the user record was created (Unix ms).',\n },\n ],\n responses: {\n oauth_token: oauthTokenSchema,\n users: usersResponseSchema,\n },\n },\n [LOGIN_EVENT]: {\n shape: 'event',\n filterable: [\n {\n field: 'type',\n ops: ['eq'],\n values: ['s', 'f', 'seacft', 'fp'],\n },\n ],\n description:\n 'Login / authentication events from the Auth0 Logs endpoint. One event per log row of type s (success), f (failure), seacft (token exchange success), or fp (failed change password).',\n endpoint: 'GET /api/v2/logs',\n notes:\n 'Uses checkpoint pagination (from = last seen log_id, take = page size) and reads every page until the endpoint returns no more rows, so a sync is not capped at 1000 events. Incremental syncs resume from the last ingested log_id; the type filter (and any since bound) is applied client-side because the checkpoint method ignores q / sort / page.',\n fields: [\n { name: 'logId', description: 'Auth0 log row id.' },\n {\n name: 'type',\n description: 'Auth0 log type (s, f, seacft, fp).',\n },\n {\n name: 'userId',\n description: 'Auth0 user_id the event belongs to (may be null).',\n },\n { name: 'ip', description: 'Source IP of the login attempt.' },\n {\n name: 'connection',\n description: 'Connection name used for the login.',\n },\n {\n name: 'strategy',\n description:\n 'Identity provider strategy (e.g. auth0, google-oauth2, samlp).',\n },\n ],\n responses: { logs: logsResponseSchema },\n },\n [DAILY_METRIC]: {\n shape: 'metric',\n description:\n 'Daily login and signup counts from the Auth0 Daily Stats endpoint, one sample per day for the configured lookback window. This is a logins/signups activity proxy, not a count of distinct active users.',\n endpoint: 'GET /api/v2/stats/daily',\n unit: 'count',\n granularity: '1d',\n dimensions: [\n {\n name: 'kind',\n description: 'Either \"logins\" or \"signups\".',\n },\n ],\n responses: { daily_stats: dailyStatsResponseSchema },\n },\n});\n\nexport const id = 'auth0';\n\ntype UsersResponse = z.infer<typeof usersResponseSchema>;\ntype LogsResponse = z.infer<typeof logsResponseSchema>;\ntype DailyStatsResponse = z.infer<typeof dailyStatsResponseSchema>;\ntype OauthTokenResponse = z.infer<typeof oauthTokenSchema>;\ntype Auth0User = z.infer<typeof userSchema>;\ntype Auth0Log = z.infer<typeof logSchema>;\ntype Auth0DailyStat = z.infer<typeof dailyStatSchema>;\n\nfunction escapeLuceneRange(iso: string): string {\n const d = new Date(iso);\n if (Number.isNaN(d.getTime())) {\n return iso;\n }\n return d.toISOString();\n}\n\nfunction isLogEventType(value: string): value is LogEventType {\n return (LOG_EVENT_TYPES as readonly string[]).includes(value);\n}\n\nfunction primaryIdentityProvider(user: Auth0User): string | null {\n const identities = user.identities ?? [];\n const first = identities[0];\n if (!first) {\n const id = user.user_id;\n const sep = id.indexOf('|');\n return sep > 0 ? id.slice(0, sep) : null;\n }\n return first.provider ?? null;\n}\n\nfunction yyyymmdd(date: Date): string {\n const y = date.getUTCFullYear();\n const m = String(date.getUTCMonth() + 1).padStart(2, '0');\n const d = String(date.getUTCDate()).padStart(2, '0');\n return `${y}${m}${d}`;\n}\n\nexport class Auth0Connector extends BaseConnector<\n Auth0Settings,\n Auth0Credentials\n> {\n static readonly id = id;\n\n static readonly resources = auth0Resources;\n\n static readonly schemas = schemasFromResources(auth0Resources);\n\n static create(input: unknown, ctx?: ConnectorContext): Auth0Connector {\n const parsed = configFields.parse(input);\n return new Auth0Connector(\n {\n domain: parsed.domain,\n resources: parsed.resources,\n statsLookbackDays: parsed.statsLookbackDays,\n },\n {\n clientId: parsed.clientId,\n clientSecret: parsed.clientSecret,\n },\n ctx,\n );\n }\n\n readonly id = id;\n override readonly credentials = auth0Credentials;\n\n private accessToken: string | null = null;\n private accessTokenExpiry: number = 0;\n\n private baseUrl(): string {\n return `https://${this.settings.domain}`;\n }\n\n private audience(): string {\n return `https://${this.settings.domain}/api/v2/`;\n }\n\n private async refreshAccessToken(signal?: AbortSignal): Promise<string> {\n const res = await this.post<OauthTokenResponse>(\n `${this.baseUrl()}/oauth/token`,\n {\n resource: 'oauth_token',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('auth0'),\n },\n body: JSON.stringify({\n grant_type: 'client_credentials',\n client_id: this.creds.clientId,\n client_secret: this.creds.clientSecret,\n audience: this.audience(),\n }),\n signal,\n },\n );\n const token = res.body.access_token;\n const expiresIn = res.body.expires_in ?? 3600;\n this.accessToken = token;\n this.accessTokenExpiry = Date.now() + (expiresIn - 60) * 1000;\n return token;\n }\n\n private async getAccessToken(signal?: AbortSignal): Promise<string> {\n if (!this.accessToken || Date.now() >= this.accessTokenExpiry) {\n return this.refreshAccessToken(signal);\n }\n return this.accessToken;\n }\n\n private async apiGet<T>(\n url: string,\n resource: string,\n signal?: AbortSignal,\n retried = false,\n ): Promise<HttpResponse<T>> {\n const token = await this.getAccessToken(signal);\n const res = await this.get<T>(url, {\n resource,\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n 'User-Agent': connectorUserAgent('auth0'),\n },\n rateLimit: auth0RateLimit,\n signal,\n });\n if (res.status === 401 && !retried) {\n this.accessToken = null;\n this.accessTokenExpiry = 0;\n return this.apiGet<T>(url, resource, signal, true);\n }\n return res;\n }\n\n private parsePageCursor(page: string | null): number {\n if (!page) {\n return 0;\n }\n const n = Number.parseInt(page, 10);\n if (!Number.isFinite(n) || n < 0) {\n return 0;\n }\n return n;\n }\n\n private buildUsersUrl(page: number, options: SyncOptions): string {\n const u = new URL(`${this.baseUrl()}/api/v2/users`);\n u.searchParams.set('page', String(page));\n u.searchParams.set('per_page', String(PAGE_SIZE));\n u.searchParams.set('include_totals', 'true');\n u.searchParams.set('sort', 'updated_at:1');\n if (options.since) {\n const iso = escapeLuceneRange(options.since);\n u.searchParams.set('q', `updated_at:[${iso} TO *]`);\n u.searchParams.set('search_engine', 'v3');\n }\n return u.toString();\n }\n\n private buildLogsUrl(from: string | null): string {\n const u = new URL(`${this.baseUrl()}/api/v2/logs`);\n u.searchParams.set('take', String(PAGE_SIZE));\n if (from) {\n u.searchParams.set('from', from);\n }\n return u.toString();\n }\n\n private buildDailyStatsUrl(options: SyncOptions): string {\n const lookback =\n this.settings.statsLookbackDays ?? DEFAULT_STATS_LOOKBACK_DAYS;\n const to = new Date();\n let from = new Date(to.getTime() - (lookback - 1) * 24 * 60 * 60 * 1000);\n if (options.since) {\n const sinceMs = Date.parse(options.since);\n if (Number.isFinite(sinceMs)) {\n const sinceDate = new Date(sinceMs);\n if (sinceDate.getTime() > from.getTime()) {\n from = sinceDate;\n }\n }\n }\n const u = new URL(`${this.baseUrl()}/api/v2/stats/daily`);\n u.searchParams.set('from', yyyymmdd(from));\n u.searchParams.set('to', yyyymmdd(to));\n return u.toString();\n }\n\n private async fetchUsersPage(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: Auth0User[]; next: string | null }> {\n const pageNum = this.parsePageCursor(page);\n const url = this.buildUsersUrl(pageNum, options);\n const res = await this.apiGet<UsersResponse>(url, 'users', signal);\n const users = res.body.users;\n const length = res.body.length ?? users.length;\n const nextPage = pageNum + 1;\n const hasMore = length >= PAGE_SIZE && nextPage < MAX_USER_PAGES;\n return { items: users, next: hasMore ? String(nextPage) : null };\n }\n\n private logCheckpoint(log: Auth0Log): string {\n return log.log_id ?? log._id;\n }\n\n private async fetchLogsPage(\n from: string | null,\n signal: AbortSignal | undefined,\n ): Promise<{ items: Auth0Log[]; next: string | null }> {\n const url = this.buildLogsUrl(from);\n const res = await this.apiGet<LogsResponse>(url, 'logs', signal);\n const logs = res.body;\n if (logs.length === 0) {\n return { items: [], next: null };\n }\n const nextFrom = this.logCheckpoint(logs[logs.length - 1]!);\n return { items: logs, next: nextFrom === from ? null : nextFrom };\n }\n\n private async lastIngestedLogId(\n storage: StorageHandle,\n ): Promise<string | null> {\n const events = await storage.queryEvents({ name: LOGIN_EVENT });\n let max: string | null = null;\n for (const e of events) {\n const logId = e.attributes.logId;\n if (typeof logId === 'string' && (max === null || logId > max)) {\n max = logId;\n }\n }\n return max;\n }\n\n private async fetchDailyStats(\n page: string | null,\n options: SyncOptions,\n signal: AbortSignal | undefined,\n ): Promise<{ items: Auth0DailyStat[]; next: string | null }> {\n if (page !== null) {\n return { items: [], next: null };\n }\n const url = this.buildDailyStatsUrl(options);\n const res = await this.apiGet<DailyStatsResponse>(\n url,\n 'daily_stats',\n signal,\n );\n return { items: res.body, next: null };\n }\n\n private async writeUsers(\n storage: StorageHandle,\n items: Auth0User[],\n ): Promise<void> {\n for (const u of items) {\n const lastLoginMs = parseEpoch(u.last_login ?? null, 'iso');\n const createdMs = parseEpoch(u.created_at ?? null, 'iso');\n const updatedMs = parseEpoch(u.updated_at ?? null, 'iso');\n await storage.entity({\n type: USER_ENTITY,\n id: u.user_id,\n attributes: {\n email: u.email ?? null,\n identityProvider: primaryIdentityProvider(u),\n lastLogin: lastLoginMs,\n loginsCount: u.logins_count ?? null,\n blocked: u.blocked ?? false,\n createdAt: createdMs,\n },\n updated_at: updatedMs ?? createdMs ?? 0,\n });\n }\n }\n\n private async writeLogs(\n storage: StorageHandle,\n items: Auth0Log[],\n sinceMs: number | null,\n ): Promise<void> {\n for (const log of items) {\n const ts = parseEpoch(log.date, 'iso');\n if (ts === null) {\n continue;\n }\n if (sinceMs !== null && ts < sinceMs) {\n continue;\n }\n if (!isLogEventType(log.type)) {\n continue;\n }\n await storage.event({\n name: LOGIN_EVENT,\n start_ts: ts,\n end_ts: null,\n attributes: {\n logId: this.logCheckpoint(log),\n type: log.type,\n userId: log.user_id ?? null,\n ip: log.ip ?? null,\n connection: log.connection ?? null,\n strategy: log.strategy ?? null,\n },\n });\n }\n }\n\n private async writeDailyStats(\n storage: StorageHandle,\n items: Auth0DailyStat[],\n ): Promise<void> {\n const samples: Array<{\n name: string;\n ts: number;\n value: number;\n attributes: Record<string, string | number>;\n }> = [];\n for (const stat of items) {\n const ts = parseEpoch(stat.date, 'iso');\n if (ts === null) {\n continue;\n }\n if (typeof stat.logins === 'number' && Number.isFinite(stat.logins)) {\n samples.push({\n name: DAILY_METRIC,\n ts,\n value: stat.logins,\n attributes: { kind: 'logins' },\n });\n }\n if (typeof stat.signups === 'number' && Number.isFinite(stat.signups)) {\n samples.push({\n name: DAILY_METRIC,\n ts,\n value: stat.signups,\n attributes: { kind: 'signups' },\n });\n }\n }\n if (samples.length > 0) {\n await storage.metrics(samples, { names: [DAILY_METRIC] });\n }\n }\n\n private async writePhase(\n storage: StorageHandle,\n phase: Auth0Phase,\n items: unknown[],\n sinceMs: number | null,\n ): Promise<void> {\n switch (phase) {\n case 'users':\n return this.writeUsers(storage, items as Auth0User[]);\n case 'login_events':\n return this.writeLogs(storage, items as Auth0Log[], sinceMs);\n case 'daily_active_users':\n return this.writeDailyStats(storage, items as Auth0DailyStat[]);\n }\n }\n\n private async clearScopeOnFirstPage(\n storage: StorageHandle,\n phase: Auth0Phase,\n isFull: boolean,\n ): Promise<void> {\n if (!isFull) {\n return;\n }\n switch (phase) {\n case 'users':\n await storage.entities([], { types: [USER_ENTITY] });\n return;\n case 'login_events':\n await storage.events([], { names: [LOGIN_EVENT] });\n return;\n case 'daily_active_users':\n await storage.metrics([], { names: [DAILY_METRIC] });\n return;\n }\n }\n\n private resolveCursor(cursor: unknown): Auth0SyncCursor | undefined {\n return isAuth0SyncCursor(cursor) ? cursor : undefined;\n }\n\n async sync(\n options: SyncOptions,\n storage: StorageHandle,\n signal?: AbortSignal,\n ): Promise<SyncResult> {\n const cursor = this.resolveCursor(options.cursor);\n const isFull = options.mode === 'full';\n\n const phases = selectActivePhases<Auth0Resource, Auth0Phase>(\n (r) => r,\n PHASE_ORDER,\n this.settings.resources,\n );\n\n const sinceMs = options.since ? Date.parse(options.since) : null;\n const logsSeed =\n !isFull && phases.includes('login_events')\n ? await this.lastIngestedLogId(storage)\n : null;\n\n return paginateChunked<Auth0Phase, string>({\n phases,\n cursor,\n signal,\n logger: this.logger,\n fetchPage: async (phase, page, sig) => {\n switch (phase) {\n case 'users':\n return this.fetchUsersPage(page, options, sig);\n case 'login_events':\n return this.fetchLogsPage(page ?? logsSeed, sig);\n case 'daily_active_users':\n return this.fetchDailyStats(page, options, sig);\n }\n },\n writeBatch: async (phase, items, page) => {\n if (page === null) {\n await this.clearScopeOnFirstPage(storage, phase, isFull);\n }\n await this.writePhase(\n storage,\n phase,\n items,\n phase === 'login_events' ? sinceMs : null,\n );\n },\n });\n }\n}\n","import { Auth0Connector } from './auth0';\n\nexport {\n Auth0Connector,\n auth0Resources as resources,\n configFields,\n doc,\n id,\n} from './auth0';\nexport type { Auth0Resource, Auth0Settings } from './auth0';\nexport default Auth0Connector;\n"],"mappings":";AEAO,IAAM,sBAAsB;AAE5B,IAAM,qBAAqB,qBAAqB,mBAAmB;AAEnE,SAAS,mBAAmB,aAA6B;AAC9D,SAAO,qBAAqB,WAAW,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
|
3
|
-
"version": "0.0
|
|
3
|
+
"version": "0.25.0",
|
|
4
4
|
"description": "Rawdash connector for Auth0 — syncs users, login events, and daily active-user / signup metrics from the Auth0 Management API into the six-shape storage model",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -22,22 +22,22 @@
|
|
|
22
22
|
"import": "./dist/index.js"
|
|
23
23
|
}
|
|
24
24
|
},
|
|
25
|
-
"scripts": {
|
|
26
|
-
"build": "tsup",
|
|
27
|
-
"typecheck": "tsc --noEmit",
|
|
28
|
-
"lint": "eslint src",
|
|
29
|
-
"test": "vitest run"
|
|
30
|
-
},
|
|
31
25
|
"dependencies": {
|
|
32
|
-
"
|
|
33
|
-
"
|
|
26
|
+
"zod": "^4.4.3",
|
|
27
|
+
"@rawdash/core": "0.25.0"
|
|
34
28
|
},
|
|
35
29
|
"devDependencies": {
|
|
36
|
-
"@rawdash/connector-shared": "workspace:*",
|
|
37
|
-
"@rawdash/connector-test-utils": "workspace:*",
|
|
38
30
|
"fast-check": "^4.8.0",
|
|
39
31
|
"tsup": "^8.0.0",
|
|
40
32
|
"typescript": "^5.7.2",
|
|
41
|
-
"vitest": "^4.1.4"
|
|
33
|
+
"vitest": "^4.1.4",
|
|
34
|
+
"@rawdash/connector-shared": "0.3.1",
|
|
35
|
+
"@rawdash/connector-test-utils": "0.0.10"
|
|
36
|
+
},
|
|
37
|
+
"scripts": {
|
|
38
|
+
"build": "tsup",
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"lint": "eslint src",
|
|
41
|
+
"test": "vitest run"
|
|
42
42
|
}
|
|
43
|
-
}
|
|
43
|
+
}
|