@rawdash/connector-auth0 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,133 @@
1
+ <!-- This file is generated from connector metadata by scripts/generate-connector-docs.ts. Do not edit by hand. -->
2
+
3
+ # @rawdash/connector-auth0
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@rawdash/connector-auth0)](https://www.npmjs.com/package/@rawdash/connector-auth0)
6
+ [![license](https://img.shields.io/npm/l/@rawdash/connector-auth0)](https://github.com/rawdash/rawdash/blob/main/LICENSE)
7
+
8
+ Sync users, login events, and daily active-user / signup metrics from an Auth0 tenant for identity, sign-up, and failed-login dashboards.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @rawdash/connector-auth0
14
+ ```
15
+
16
+ ## Authentication
17
+
18
+ OAuth 2.0 client-credentials flow against a Machine-to-Machine application authorized for the Auth0 Management API.
19
+
20
+ 1. In the Auth0 Dashboard, open Applications -> Applications and create a new Machine to Machine Application.
21
+ 2. Authorize the M2M app for the Auth0 Management API (Applications -> APIs -> Auth0 Management API -> Machine to Machine Applications).
22
+ 3. 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).
23
+ 4. Copy the Domain (e.g. "acme.us.auth0.com"), Client ID, and Client Secret from the M2M application Settings tab.
24
+ 5. Store the client secret as a rawdash secret and reference it from the connector config as `clientSecret: secret("AUTH0_CLIENT_SECRET")`.
25
+
26
+ ## Configuration
27
+
28
+ | Field | Type | Required | Description |
29
+ | ------------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
30
+ | `domain` | string | Yes | 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. |
31
+ | `clientId` | string | Yes | Client ID of the Auth0 Machine-to-Machine application authorized to call the Management API. |
32
+ | `clientSecret` | secret | Yes | Client secret of the Auth0 Machine-to-Machine application. Stored as a secret. |
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-active-user / signup stats to refresh on each sync. Defaults to 30 (the maximum the Auth0 Daily Stats endpoint returns). |
35
+
36
+ ## Resources
37
+
38
+ - **`auth0_user`** _(entity)_ - Auth0 users keyed by user_id, with email, primary identity provider, last login, login count, and blocked flag.
39
+ - Endpoint: `GET /api/v2/users`
40
+ - 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.
41
+ - `email`: Primary email address.
42
+ - `identityProvider`: Provider of the primary identity (e.g. auth0, google-oauth2, samlp).
43
+ - `lastLogin`: Most recent login timestamp (Unix ms).
44
+ - `loginsCount`: Total successful logins (counter maintained by Auth0).
45
+ - `blocked`: Whether the user has been administratively blocked.
46
+ - `createdAt`: When the user record was created (Unix ms).
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
+ - Endpoint: `GET /api/v2/logs`
49
+ - 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.
50
+ - `logId`: Auth0 log row id.
51
+ - `type`: Auth0 log type (s, f, seacft, fp).
52
+ - `userId`: Auth0 user_id the event belongs to (may be null).
53
+ - `ip`: Source IP of the login attempt.
54
+ - `connection`: Connection name used for the login.
55
+ - `strategy`: Identity provider strategy (e.g. auth0, google-oauth2, samlp).
56
+ - **`auth0_daily_active_users`** _(metric)_ - Daily logins and signups, one sample per day for the configured lookback window (up to 30 days, the Daily Stats endpoint maximum).
57
+ - Endpoint: `GET /api/v2/stats/daily`
58
+ - Unit: count
59
+ - Granularity: 1d
60
+ - Dimensions: `kind`
61
+
62
+ ## Example
63
+
64
+ ```ts
65
+ import {
66
+ defineConfig,
67
+ defineDashboard,
68
+ defineMetric,
69
+ secret,
70
+ } from '@rawdash/core';
71
+
72
+ const auth0 = {
73
+ name: 'auth0',
74
+ connectorId: 'auth0',
75
+ config: {
76
+ domain: 'acme.us.auth0.com',
77
+ clientId: 'AbCdEf...',
78
+ clientSecret: secret('AUTH0_CLIENT_SECRET'),
79
+ },
80
+ };
81
+
82
+ export default defineConfig({
83
+ connectors: [auth0],
84
+ dashboards: {
85
+ identity: defineDashboard({
86
+ widgets: {
87
+ active_users: {
88
+ kind: 'stat',
89
+ title: 'Auth0 users',
90
+ metric: defineMetric({
91
+ connector: auth0,
92
+ shape: 'entity',
93
+ entityType: 'auth0_user',
94
+ fn: 'count',
95
+ filter: [{ field: 'blocked', op: 'eq', value: false }],
96
+ }),
97
+ },
98
+ failed_logins: {
99
+ kind: 'stat',
100
+ title: 'Failed logins',
101
+ metric: defineMetric({
102
+ connector: auth0,
103
+ shape: 'event',
104
+ name: 'auth0_login_event',
105
+ fn: 'count',
106
+ filter: [{ field: 'type', op: 'eq', value: 'f' }],
107
+ }),
108
+ },
109
+ },
110
+ }),
111
+ },
112
+ });
113
+ ```
114
+
115
+ ## Rate limits
116
+
117
+ 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.
118
+
119
+ ## Limitations
120
+
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
+ - Action / hook / branding configuration objects are out of scope.
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
+
125
+ ## Links
126
+
127
+ - [Rawdash docs](https://rawdash.dev/docs/connectors/)
128
+ - [Auth0 API docs](https://auth0.com/docs/api/management/v2)
129
+ - [GitHub](https://github.com/rawdash/rawdash)
130
+
131
+ ## License
132
+
133
+ Apache-2.0
@@ -0,0 +1,381 @@
1
+ import { BaseConnector, ConnectorContext, SyncOptions, StorageHandle, SyncResult, ConnectorDoc } from '@rawdash/core';
2
+ import { z } from 'zod';
3
+
4
+ declare const configFields: z.ZodObject<{
5
+ domain: z.ZodString;
6
+ clientId: z.ZodString;
7
+ clientSecret: z.ZodObject<{
8
+ $secret: z.ZodString;
9
+ }, z.core.$strip>;
10
+ resources: z.ZodOptional<z.ZodArray<z.ZodEnum<{
11
+ users: "users";
12
+ login_events: "login_events";
13
+ daily_active_users: "daily_active_users";
14
+ }>>>;
15
+ statsLookbackDays: z.ZodOptional<z.ZodNumber>;
16
+ }, z.core.$strip>;
17
+ declare const doc: ConnectorDoc;
18
+ type Auth0Resource = 'users' | 'login_events' | 'daily_active_users';
19
+ interface Auth0Settings {
20
+ domain: string;
21
+ resources?: readonly Auth0Resource[];
22
+ statsLookbackDays?: number;
23
+ }
24
+ declare const auth0Credentials: {
25
+ clientId: {
26
+ description: string;
27
+ auth: "required";
28
+ };
29
+ clientSecret: {
30
+ description: string;
31
+ auth: "required";
32
+ };
33
+ };
34
+ type Auth0Credentials = typeof auth0Credentials;
35
+ declare const auth0Resources: {
36
+ readonly auth0_user: {
37
+ readonly shape: "entity";
38
+ readonly filterable: [{
39
+ readonly field: "blocked";
40
+ readonly ops: ["eq"];
41
+ readonly values: ["true", "false"];
42
+ }, {
43
+ readonly field: "identityProvider";
44
+ readonly ops: ["eq"];
45
+ }];
46
+ readonly description: "Auth0 users keyed by user_id, with email, primary identity provider, last login, login count, and blocked flag.";
47
+ readonly endpoint: "GET /api/v2/users";
48
+ readonly notes: "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.";
49
+ readonly fields: [{
50
+ readonly name: "email";
51
+ readonly description: "Primary email address.";
52
+ }, {
53
+ readonly name: "identityProvider";
54
+ readonly description: "Provider of the primary identity (e.g. auth0, google-oauth2, samlp).";
55
+ }, {
56
+ readonly name: "lastLogin";
57
+ readonly description: "Most recent login timestamp (Unix ms).";
58
+ }, {
59
+ readonly name: "loginsCount";
60
+ readonly description: "Total successful logins (counter maintained by Auth0).";
61
+ }, {
62
+ readonly name: "blocked";
63
+ readonly description: "Whether the user has been administratively blocked.";
64
+ }, {
65
+ readonly name: "createdAt";
66
+ readonly description: "When the user record was created (Unix ms).";
67
+ }];
68
+ readonly responses: {
69
+ readonly oauth_token: z.ZodObject<{
70
+ access_token: z.ZodString;
71
+ token_type: z.ZodOptional<z.ZodString>;
72
+ expires_in: z.ZodOptional<z.ZodNumber>;
73
+ }, z.core.$strip>;
74
+ readonly users: z.ZodObject<{
75
+ start: z.ZodOptional<z.ZodNumber>;
76
+ limit: z.ZodOptional<z.ZodNumber>;
77
+ length: z.ZodOptional<z.ZodNumber>;
78
+ total: z.ZodOptional<z.ZodNumber>;
79
+ users: z.ZodArray<z.ZodObject<{
80
+ user_id: z.ZodString;
81
+ email: z.ZodOptional<z.ZodNullable<z.ZodString>>;
82
+ email_verified: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
83
+ identities: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
84
+ connection: z.ZodOptional<z.ZodNullable<z.ZodString>>;
85
+ provider: z.ZodOptional<z.ZodNullable<z.ZodString>>;
86
+ user_id: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
87
+ isSocial: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
88
+ }, z.core.$strip>>>>;
89
+ last_login: z.ZodOptional<z.ZodNullable<z.ZodString>>;
90
+ logins_count: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
91
+ created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
92
+ updated_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
93
+ blocked: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
94
+ }, z.core.$strip>>;
95
+ }, z.core.$strip>;
96
+ };
97
+ };
98
+ readonly auth0_login_event: {
99
+ readonly shape: "event";
100
+ readonly filterable: [{
101
+ readonly field: "type";
102
+ readonly ops: ["eq"];
103
+ readonly values: ["s", "f", "seacft", "fp"];
104
+ }];
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
+ readonly endpoint: "GET /api/v2/logs";
107
+ readonly notes: "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.";
108
+ readonly fields: [{
109
+ readonly name: "logId";
110
+ readonly description: "Auth0 log row id.";
111
+ }, {
112
+ readonly name: "type";
113
+ readonly description: "Auth0 log type (s, f, seacft, fp).";
114
+ }, {
115
+ readonly name: "userId";
116
+ readonly description: "Auth0 user_id the event belongs to (may be null).";
117
+ }, {
118
+ readonly name: "ip";
119
+ readonly description: "Source IP of the login attempt.";
120
+ }, {
121
+ readonly name: "connection";
122
+ readonly description: "Connection name used for the login.";
123
+ }, {
124
+ readonly name: "strategy";
125
+ readonly description: "Identity provider strategy (e.g. auth0, google-oauth2, samlp).";
126
+ }];
127
+ readonly responses: {
128
+ readonly logs: z.ZodArray<z.ZodObject<{
129
+ _id: z.ZodString;
130
+ log_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
131
+ date: z.ZodString;
132
+ type: z.ZodString;
133
+ user_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
134
+ user_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
135
+ client_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
136
+ ip: z.ZodOptional<z.ZodNullable<z.ZodString>>;
137
+ connection: z.ZodOptional<z.ZodNullable<z.ZodString>>;
138
+ strategy: z.ZodOptional<z.ZodNullable<z.ZodString>>;
139
+ }, z.core.$strip>>;
140
+ };
141
+ };
142
+ readonly auth0_daily_active_users: {
143
+ readonly shape: "metric";
144
+ readonly description: "Daily logins and signups, one sample per day for the configured lookback window (up to 30 days, the Daily Stats endpoint maximum).";
145
+ readonly endpoint: "GET /api/v2/stats/daily";
146
+ readonly unit: "count";
147
+ readonly granularity: "1d";
148
+ readonly dimensions: [{
149
+ readonly name: "kind";
150
+ readonly description: "Either \"logins\" or \"signups\".";
151
+ }];
152
+ readonly responses: {
153
+ readonly daily_stats: z.ZodArray<z.ZodObject<{
154
+ date: z.ZodString;
155
+ logins: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
156
+ signups: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
157
+ leaked_passwords: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
158
+ updated_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
159
+ created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
160
+ }, z.core.$strip>>;
161
+ };
162
+ };
163
+ };
164
+ declare const id = "auth0";
165
+ declare class Auth0Connector extends BaseConnector<Auth0Settings, Auth0Credentials> {
166
+ static readonly id = "auth0";
167
+ static readonly resources: {
168
+ readonly auth0_user: {
169
+ readonly shape: "entity";
170
+ readonly filterable: [{
171
+ readonly field: "blocked";
172
+ readonly ops: ["eq"];
173
+ readonly values: ["true", "false"];
174
+ }, {
175
+ readonly field: "identityProvider";
176
+ readonly ops: ["eq"];
177
+ }];
178
+ readonly description: "Auth0 users keyed by user_id, with email, primary identity provider, last login, login count, and blocked flag.";
179
+ readonly endpoint: "GET /api/v2/users";
180
+ readonly notes: "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.";
181
+ readonly fields: [{
182
+ readonly name: "email";
183
+ readonly description: "Primary email address.";
184
+ }, {
185
+ readonly name: "identityProvider";
186
+ readonly description: "Provider of the primary identity (e.g. auth0, google-oauth2, samlp).";
187
+ }, {
188
+ readonly name: "lastLogin";
189
+ readonly description: "Most recent login timestamp (Unix ms).";
190
+ }, {
191
+ readonly name: "loginsCount";
192
+ readonly description: "Total successful logins (counter maintained by Auth0).";
193
+ }, {
194
+ readonly name: "blocked";
195
+ readonly description: "Whether the user has been administratively blocked.";
196
+ }, {
197
+ readonly name: "createdAt";
198
+ readonly description: "When the user record was created (Unix ms).";
199
+ }];
200
+ readonly responses: {
201
+ readonly oauth_token: z.ZodObject<{
202
+ access_token: z.ZodString;
203
+ token_type: z.ZodOptional<z.ZodString>;
204
+ expires_in: z.ZodOptional<z.ZodNumber>;
205
+ }, z.core.$strip>;
206
+ readonly users: z.ZodObject<{
207
+ start: z.ZodOptional<z.ZodNumber>;
208
+ limit: z.ZodOptional<z.ZodNumber>;
209
+ length: z.ZodOptional<z.ZodNumber>;
210
+ total: z.ZodOptional<z.ZodNumber>;
211
+ users: z.ZodArray<z.ZodObject<{
212
+ user_id: z.ZodString;
213
+ email: z.ZodOptional<z.ZodNullable<z.ZodString>>;
214
+ email_verified: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
215
+ identities: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
216
+ connection: z.ZodOptional<z.ZodNullable<z.ZodString>>;
217
+ provider: z.ZodOptional<z.ZodNullable<z.ZodString>>;
218
+ user_id: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
219
+ isSocial: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
220
+ }, z.core.$strip>>>>;
221
+ last_login: z.ZodOptional<z.ZodNullable<z.ZodString>>;
222
+ logins_count: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
223
+ created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
224
+ updated_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
225
+ blocked: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
226
+ }, z.core.$strip>>;
227
+ }, z.core.$strip>;
228
+ };
229
+ };
230
+ readonly auth0_login_event: {
231
+ readonly shape: "event";
232
+ readonly filterable: [{
233
+ readonly field: "type";
234
+ readonly ops: ["eq"];
235
+ readonly values: ["s", "f", "seacft", "fp"];
236
+ }];
237
+ 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
+ readonly endpoint: "GET /api/v2/logs";
239
+ readonly notes: "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.";
240
+ readonly fields: [{
241
+ readonly name: "logId";
242
+ readonly description: "Auth0 log row id.";
243
+ }, {
244
+ readonly name: "type";
245
+ readonly description: "Auth0 log type (s, f, seacft, fp).";
246
+ }, {
247
+ readonly name: "userId";
248
+ readonly description: "Auth0 user_id the event belongs to (may be null).";
249
+ }, {
250
+ readonly name: "ip";
251
+ readonly description: "Source IP of the login attempt.";
252
+ }, {
253
+ readonly name: "connection";
254
+ readonly description: "Connection name used for the login.";
255
+ }, {
256
+ readonly name: "strategy";
257
+ readonly description: "Identity provider strategy (e.g. auth0, google-oauth2, samlp).";
258
+ }];
259
+ readonly responses: {
260
+ readonly logs: z.ZodArray<z.ZodObject<{
261
+ _id: z.ZodString;
262
+ log_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
263
+ date: z.ZodString;
264
+ type: z.ZodString;
265
+ user_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
266
+ user_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
267
+ client_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
268
+ ip: z.ZodOptional<z.ZodNullable<z.ZodString>>;
269
+ connection: z.ZodOptional<z.ZodNullable<z.ZodString>>;
270
+ strategy: z.ZodOptional<z.ZodNullable<z.ZodString>>;
271
+ }, z.core.$strip>>;
272
+ };
273
+ };
274
+ readonly auth0_daily_active_users: {
275
+ readonly shape: "metric";
276
+ readonly description: "Daily logins and signups, one sample per day for the configured lookback window (up to 30 days, the Daily Stats endpoint maximum).";
277
+ readonly endpoint: "GET /api/v2/stats/daily";
278
+ readonly unit: "count";
279
+ readonly granularity: "1d";
280
+ readonly dimensions: [{
281
+ readonly name: "kind";
282
+ readonly description: "Either \"logins\" or \"signups\".";
283
+ }];
284
+ readonly responses: {
285
+ readonly daily_stats: z.ZodArray<z.ZodObject<{
286
+ date: z.ZodString;
287
+ logins: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
288
+ signups: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
289
+ leaked_passwords: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
290
+ updated_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
291
+ created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
292
+ }, z.core.$strip>>;
293
+ };
294
+ };
295
+ };
296
+ static readonly schemas: {
297
+ readonly oauth_token: z.ZodObject<{
298
+ access_token: z.ZodString;
299
+ token_type: z.ZodOptional<z.ZodString>;
300
+ expires_in: z.ZodOptional<z.ZodNumber>;
301
+ }, z.core.$strip>;
302
+ readonly users: z.ZodObject<{
303
+ start: z.ZodOptional<z.ZodNumber>;
304
+ limit: z.ZodOptional<z.ZodNumber>;
305
+ length: z.ZodOptional<z.ZodNumber>;
306
+ total: z.ZodOptional<z.ZodNumber>;
307
+ users: z.ZodArray<z.ZodObject<{
308
+ user_id: z.ZodString;
309
+ email: z.ZodOptional<z.ZodNullable<z.ZodString>>;
310
+ email_verified: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
311
+ identities: z.ZodOptional<z.ZodNullable<z.ZodArray<z.ZodObject<{
312
+ connection: z.ZodOptional<z.ZodNullable<z.ZodString>>;
313
+ provider: z.ZodOptional<z.ZodNullable<z.ZodString>>;
314
+ user_id: z.ZodOptional<z.ZodNullable<z.ZodUnion<readonly [z.ZodString, z.ZodNumber]>>>;
315
+ isSocial: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
316
+ }, z.core.$strip>>>>;
317
+ last_login: z.ZodOptional<z.ZodNullable<z.ZodString>>;
318
+ logins_count: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
319
+ created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
320
+ updated_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
321
+ blocked: z.ZodOptional<z.ZodNullable<z.ZodBoolean>>;
322
+ }, z.core.$strip>>;
323
+ }, z.core.$strip>;
324
+ } & {
325
+ readonly logs: z.ZodArray<z.ZodObject<{
326
+ _id: z.ZodString;
327
+ log_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
328
+ date: z.ZodString;
329
+ type: z.ZodString;
330
+ user_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
331
+ user_name: z.ZodOptional<z.ZodNullable<z.ZodString>>;
332
+ client_id: z.ZodOptional<z.ZodNullable<z.ZodString>>;
333
+ ip: z.ZodOptional<z.ZodNullable<z.ZodString>>;
334
+ connection: z.ZodOptional<z.ZodNullable<z.ZodString>>;
335
+ strategy: z.ZodOptional<z.ZodNullable<z.ZodString>>;
336
+ }, z.core.$strip>>;
337
+ } & {
338
+ readonly daily_stats: z.ZodArray<z.ZodObject<{
339
+ date: z.ZodString;
340
+ logins: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
341
+ signups: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
342
+ leaked_passwords: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
343
+ updated_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
344
+ created_at: z.ZodOptional<z.ZodNullable<z.ZodString>>;
345
+ }, z.core.$strip>>;
346
+ } & Readonly<Record<string, z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>>>;
347
+ static create(input: unknown, ctx?: ConnectorContext): Auth0Connector;
348
+ readonly id = "auth0";
349
+ readonly credentials: {
350
+ clientId: {
351
+ description: string;
352
+ auth: "required";
353
+ };
354
+ clientSecret: {
355
+ description: string;
356
+ auth: "required";
357
+ };
358
+ };
359
+ private accessToken;
360
+ private baseUrl;
361
+ private audience;
362
+ private refreshAccessToken;
363
+ private getAccessToken;
364
+ private apiGet;
365
+ private parsePageCursor;
366
+ private buildUsersUrl;
367
+ private buildLogsUrl;
368
+ private buildDailyStatsUrl;
369
+ private fetchUsersPage;
370
+ private fetchLogsPage;
371
+ private fetchDailyStats;
372
+ private writeUsers;
373
+ private writeLogs;
374
+ private writeDailyStats;
375
+ private writePhase;
376
+ private clearScopeOnFirstPage;
377
+ private resolveCursor;
378
+ sync(options: SyncOptions, storage: StorageHandle, signal?: AbortSignal): Promise<SyncResult>;
379
+ }
380
+
381
+ export { Auth0Connector, type Auth0Resource, type Auth0Settings, configFields, Auth0Connector as default, doc, id, auth0Resources as resources };
package/dist/index.js ADDED
@@ -0,0 +1,627 @@
1
+ // ../../connector-shared/dist/index.js
2
+ var HTTP_CLIENT_VERSION = "0.0.0";
3
+ var DEFAULT_USER_AGENT = `rawdash-connector/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
4
+ function connectorUserAgent(connectorId) {
5
+ return `rawdash-connector-${connectorId}/${HTTP_CLIENT_VERSION} (+https://rawdash.dev)`;
6
+ }
7
+ function standardRateLimitPolicy(config) {
8
+ const { remainingHeader, resetHeader, resetUnit, resetFallbackMs } = config;
9
+ const multiplier = resetUnit === "s" ? 1e3 : 1;
10
+ return {
11
+ parse(h) {
12
+ const remainingRaw = h.get(remainingHeader);
13
+ if (remainingRaw === null || remainingRaw.trim() === "") {
14
+ return null;
15
+ }
16
+ const remaining = Number(remainingRaw);
17
+ if (!Number.isFinite(remaining)) {
18
+ return null;
19
+ }
20
+ const resetRaw = h.get(resetHeader);
21
+ if (resetRaw === null) {
22
+ if (resetFallbackMs === void 0) {
23
+ return null;
24
+ }
25
+ return {
26
+ remaining,
27
+ resetAt: new Date(Date.now() + resetFallbackMs)
28
+ };
29
+ }
30
+ if (resetRaw.trim() === "") {
31
+ return null;
32
+ }
33
+ const reset = Number(resetRaw);
34
+ if (!Number.isFinite(reset) || reset < 0) {
35
+ return null;
36
+ }
37
+ const resetMs = reset * multiplier;
38
+ if (!Number.isFinite(resetMs)) {
39
+ return null;
40
+ }
41
+ return { remaining, resetAt: new Date(resetMs) };
42
+ }
43
+ };
44
+ }
45
+ function parseEpoch(value, unit) {
46
+ if (value === null || value === void 0) {
47
+ return null;
48
+ }
49
+ if (unit === "iso") {
50
+ if (typeof value !== "string") {
51
+ return null;
52
+ }
53
+ const ms = new Date(value).getTime();
54
+ return Number.isFinite(ms) ? ms : null;
55
+ }
56
+ if (typeof value === "string" && value.trim() === "") {
57
+ return null;
58
+ }
59
+ const n = typeof value === "number" ? value : Number(value);
60
+ if (!Number.isFinite(n)) {
61
+ return null;
62
+ }
63
+ const result = unit === "s" ? n * 1e3 : n;
64
+ return Number.isFinite(result) ? result : null;
65
+ }
66
+
67
+ // src/auth0.ts
68
+ import {
69
+ BaseConnector,
70
+ defineConfigFields,
71
+ defineConnectorDoc,
72
+ defineResources,
73
+ makeChunkedCursorGuard,
74
+ paginateChunked,
75
+ schemasFromResources,
76
+ selectActivePhases
77
+ } from "@rawdash/core";
78
+ import { z } from "zod";
79
+ var configFields = defineConfigFields(
80
+ z.object({
81
+ domain: z.string().min(1).regex(
82
+ /^[a-z0-9-]+(\.[a-z0-9-]+)*\.auth0\.com$/i,
83
+ 'Auth0 tenant domain, e.g. "acme.us.auth0.com" (no scheme).'
84
+ ).meta({
85
+ label: "Tenant domain",
86
+ description: '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.',
87
+ placeholder: "acme.us.auth0.com"
88
+ }),
89
+ clientId: z.string().min(1).meta({
90
+ label: "M2M application client ID",
91
+ description: "Client ID of the Auth0 Machine-to-Machine application authorized to call the Management API.",
92
+ placeholder: "AbCdEf..."
93
+ }),
94
+ clientSecret: z.object({ $secret: z.string().min(1) }).meta({
95
+ label: "M2M application client secret",
96
+ description: "Client secret of the Auth0 Machine-to-Machine application. Stored as a secret.",
97
+ placeholder: "AUTH0_CLIENT_SECRET",
98
+ secret: true
99
+ }),
100
+ resources: z.array(z.enum(["users", "login_events", "daily_active_users"])).nonempty().optional().meta({
101
+ label: "Resources",
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
+ }),
104
+ statsLookbackDays: z.number().int().positive().max(30).optional().meta({
105
+ label: "Stats lookback (days)",
106
+ description: "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).",
107
+ placeholder: "30"
108
+ })
109
+ })
110
+ );
111
+ var doc = defineConnectorDoc({
112
+ displayName: "Auth0",
113
+ category: "security",
114
+ brandColor: "#EB5424",
115
+ tagline: "Sync users, login events, and daily active-user / signup metrics from an Auth0 tenant for identity, sign-up, and failed-login dashboards.",
116
+ vendor: {
117
+ name: "Auth0",
118
+ domain: "auth0.com",
119
+ apiDocs: "https://auth0.com/docs/api/management/v2",
120
+ website: "https://auth0.com"
121
+ },
122
+ auth: {
123
+ summary: "OAuth 2.0 client-credentials flow against a Machine-to-Machine application authorized for the Auth0 Management API.",
124
+ setup: [
125
+ "In the Auth0 Dashboard, open Applications -> Applications and create a new Machine to Machine Application.",
126
+ "Authorize the M2M app for the Auth0 Management API (Applications -> APIs -> Auth0 Management API -> Machine to Machine Applications).",
127
+ "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).",
128
+ 'Copy the Domain (e.g. "acme.us.auth0.com"), Client ID, and Client Secret from the M2M application Settings tab.',
129
+ 'Store the client secret as a rawdash secret and reference it from the connector config as `clientSecret: secret("AUTH0_CLIENT_SECRET")`.'
130
+ ]
131
+ },
132
+ rateLimit: "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.",
133
+ limitations: [
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
+ "Action / hook / branding configuration objects are out of scope.",
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
+ ]
138
+ });
139
+ var auth0Credentials = {
140
+ clientId: {
141
+ description: "Auth0 Machine-to-Machine application client ID",
142
+ auth: "required"
143
+ },
144
+ clientSecret: {
145
+ description: "Auth0 Machine-to-Machine application client secret",
146
+ auth: "required"
147
+ }
148
+ };
149
+ var auth0RateLimit = standardRateLimitPolicy({
150
+ remainingHeader: "x-ratelimit-remaining",
151
+ resetHeader: "x-ratelimit-reset",
152
+ resetUnit: "s"
153
+ });
154
+ var PHASE_ORDER = ["users", "login_events", "daily_active_users"];
155
+ var isAuth0SyncCursor = makeChunkedCursorGuard(PHASE_ORDER);
156
+ var USER_ENTITY = "auth0_user";
157
+ var LOGIN_EVENT = "auth0_login_event";
158
+ var DAILY_METRIC = "auth0_daily_active_users";
159
+ var PAGE_SIZE = 100;
160
+ var MAX_USER_PAGES = 10;
161
+ var DEFAULT_STATS_LOOKBACK_DAYS = 30;
162
+ var LOG_EVENT_TYPES = ["s", "f", "seacft", "fp"];
163
+ var idString = z.string().min(1);
164
+ var oauthTokenSchema = z.object({
165
+ access_token: z.string().min(1),
166
+ token_type: z.string().optional(),
167
+ expires_in: z.number().optional()
168
+ });
169
+ var userIdentitySchema = z.object({
170
+ connection: z.string().nullish(),
171
+ provider: z.string().nullish(),
172
+ user_id: z.union([z.string(), z.number()]).nullish(),
173
+ isSocial: z.boolean().nullish()
174
+ });
175
+ var userSchema = z.object({
176
+ user_id: idString,
177
+ email: z.string().nullish(),
178
+ email_verified: z.boolean().nullish(),
179
+ identities: z.array(userIdentitySchema).nullish(),
180
+ last_login: z.string().nullish(),
181
+ logins_count: z.number().nullish(),
182
+ created_at: z.string().nullish(),
183
+ updated_at: z.string().nullish(),
184
+ blocked: z.boolean().nullish()
185
+ });
186
+ var usersResponseSchema = z.object({
187
+ start: z.number().optional(),
188
+ limit: z.number().optional(),
189
+ length: z.number().optional(),
190
+ total: z.number().optional(),
191
+ users: z.array(userSchema)
192
+ });
193
+ var logSchema = z.object({
194
+ _id: idString,
195
+ log_id: z.string().nullish(),
196
+ date: z.string(),
197
+ type: z.string(),
198
+ user_id: z.string().nullish(),
199
+ user_name: z.string().nullish(),
200
+ client_id: z.string().nullish(),
201
+ ip: z.string().nullish(),
202
+ connection: z.string().nullish(),
203
+ strategy: z.string().nullish()
204
+ });
205
+ var logsResponseSchema = z.array(logSchema);
206
+ var dailyStatSchema = z.object({
207
+ date: z.string(),
208
+ logins: z.number().nullish(),
209
+ signups: z.number().nullish(),
210
+ leaked_passwords: z.number().nullish(),
211
+ updated_at: z.string().nullish(),
212
+ created_at: z.string().nullish()
213
+ });
214
+ var dailyStatsResponseSchema = z.array(dailyStatSchema);
215
+ var auth0Resources = defineResources({
216
+ [USER_ENTITY]: {
217
+ shape: "entity",
218
+ filterable: [
219
+ { field: "blocked", ops: ["eq"], values: ["true", "false"] },
220
+ { field: "identityProvider", ops: ["eq"] }
221
+ ],
222
+ description: "Auth0 users keyed by user_id, with email, primary identity provider, last login, login count, and blocked flag.",
223
+ endpoint: "GET /api/v2/users",
224
+ notes: "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.",
225
+ fields: [
226
+ { name: "email", description: "Primary email address." },
227
+ {
228
+ name: "identityProvider",
229
+ description: "Provider of the primary identity (e.g. auth0, google-oauth2, samlp)."
230
+ },
231
+ {
232
+ name: "lastLogin",
233
+ description: "Most recent login timestamp (Unix ms)."
234
+ },
235
+ {
236
+ name: "loginsCount",
237
+ description: "Total successful logins (counter maintained by Auth0)."
238
+ },
239
+ {
240
+ name: "blocked",
241
+ description: "Whether the user has been administratively blocked."
242
+ },
243
+ {
244
+ name: "createdAt",
245
+ description: "When the user record was created (Unix ms)."
246
+ }
247
+ ],
248
+ responses: {
249
+ oauth_token: oauthTokenSchema,
250
+ users: usersResponseSchema
251
+ }
252
+ },
253
+ [LOGIN_EVENT]: {
254
+ shape: "event",
255
+ filterable: [
256
+ {
257
+ field: "type",
258
+ ops: ["eq"],
259
+ values: ["s", "f", "seacft", "fp"]
260
+ }
261
+ ],
262
+ 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
+ endpoint: "GET /api/v2/logs",
264
+ notes: "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.",
265
+ fields: [
266
+ { name: "logId", description: "Auth0 log row id." },
267
+ {
268
+ name: "type",
269
+ description: "Auth0 log type (s, f, seacft, fp)."
270
+ },
271
+ {
272
+ name: "userId",
273
+ description: "Auth0 user_id the event belongs to (may be null)."
274
+ },
275
+ { name: "ip", description: "Source IP of the login attempt." },
276
+ {
277
+ name: "connection",
278
+ description: "Connection name used for the login."
279
+ },
280
+ {
281
+ name: "strategy",
282
+ description: "Identity provider strategy (e.g. auth0, google-oauth2, samlp)."
283
+ }
284
+ ],
285
+ responses: { logs: logsResponseSchema }
286
+ },
287
+ [DAILY_METRIC]: {
288
+ shape: "metric",
289
+ description: "Daily logins and signups, one sample per day for the configured lookback window (up to 30 days, the Daily Stats endpoint maximum).",
290
+ endpoint: "GET /api/v2/stats/daily",
291
+ unit: "count",
292
+ granularity: "1d",
293
+ dimensions: [
294
+ {
295
+ name: "kind",
296
+ description: 'Either "logins" or "signups".'
297
+ }
298
+ ],
299
+ responses: { daily_stats: dailyStatsResponseSchema }
300
+ }
301
+ });
302
+ var id = "auth0";
303
+ function escapeLuceneRange(iso) {
304
+ const d = new Date(iso);
305
+ if (Number.isNaN(d.getTime())) {
306
+ return iso;
307
+ }
308
+ return d.toISOString();
309
+ }
310
+ function isLogEventType(value) {
311
+ return LOG_EVENT_TYPES.includes(value);
312
+ }
313
+ function primaryIdentityProvider(user) {
314
+ const identities = user.identities ?? [];
315
+ const first = identities[0];
316
+ if (!first) {
317
+ const id2 = user.user_id;
318
+ const sep = id2.indexOf("|");
319
+ return sep > 0 ? id2.slice(0, sep) : null;
320
+ }
321
+ return first.provider ?? null;
322
+ }
323
+ function yyyymmdd(date) {
324
+ const y = date.getUTCFullYear();
325
+ const m = String(date.getUTCMonth() + 1).padStart(2, "0");
326
+ const d = String(date.getUTCDate()).padStart(2, "0");
327
+ return `${y}${m}${d}`;
328
+ }
329
+ var Auth0Connector = class _Auth0Connector extends BaseConnector {
330
+ static id = id;
331
+ static resources = auth0Resources;
332
+ static schemas = schemasFromResources(auth0Resources);
333
+ static create(input, ctx) {
334
+ const parsed = configFields.parse(input);
335
+ return new _Auth0Connector(
336
+ {
337
+ domain: parsed.domain,
338
+ resources: parsed.resources,
339
+ statsLookbackDays: parsed.statsLookbackDays
340
+ },
341
+ {
342
+ clientId: parsed.clientId,
343
+ clientSecret: parsed.clientSecret
344
+ },
345
+ ctx
346
+ );
347
+ }
348
+ id = id;
349
+ credentials = auth0Credentials;
350
+ accessToken = null;
351
+ baseUrl() {
352
+ return `https://${this.settings.domain}`;
353
+ }
354
+ audience() {
355
+ return `https://${this.settings.domain}/api/v2/`;
356
+ }
357
+ async refreshAccessToken(signal) {
358
+ const res = await this.post(
359
+ `${this.baseUrl()}/oauth/token`,
360
+ {
361
+ resource: "oauth_token",
362
+ headers: {
363
+ "Content-Type": "application/json",
364
+ Accept: "application/json",
365
+ "User-Agent": connectorUserAgent("auth0")
366
+ },
367
+ body: JSON.stringify({
368
+ grant_type: "client_credentials",
369
+ client_id: this.creds.clientId,
370
+ client_secret: this.creds.clientSecret,
371
+ audience: this.audience()
372
+ }),
373
+ signal
374
+ }
375
+ );
376
+ return res.body.access_token;
377
+ }
378
+ async getAccessToken(signal) {
379
+ if (!this.accessToken) {
380
+ this.accessToken = await this.refreshAccessToken(signal);
381
+ }
382
+ return this.accessToken;
383
+ }
384
+ async apiGet(url, resource, signal) {
385
+ const token = await this.getAccessToken(signal);
386
+ return this.get(url, {
387
+ resource,
388
+ headers: {
389
+ Authorization: `Bearer ${token}`,
390
+ Accept: "application/json",
391
+ "User-Agent": connectorUserAgent("auth0")
392
+ },
393
+ rateLimit: auth0RateLimit,
394
+ signal
395
+ });
396
+ }
397
+ parsePageCursor(page) {
398
+ if (!page) {
399
+ return 0;
400
+ }
401
+ const n = Number.parseInt(page, 10);
402
+ if (!Number.isFinite(n) || n < 0) {
403
+ return 0;
404
+ }
405
+ return n;
406
+ }
407
+ buildUsersUrl(page, options) {
408
+ const u = new URL(`${this.baseUrl()}/api/v2/users`);
409
+ u.searchParams.set("page", String(page));
410
+ u.searchParams.set("per_page", String(PAGE_SIZE));
411
+ u.searchParams.set("include_totals", "true");
412
+ u.searchParams.set("sort", "updated_at:1");
413
+ if (options.since) {
414
+ const iso = escapeLuceneRange(options.since);
415
+ u.searchParams.set("q", `updated_at:[${iso} TO *]`);
416
+ u.searchParams.set("search_engine", "v3");
417
+ }
418
+ return u.toString();
419
+ }
420
+ buildLogsUrl(page, options) {
421
+ const u = new URL(`${this.baseUrl()}/api/v2/logs`);
422
+ u.searchParams.set("page", String(page));
423
+ u.searchParams.set("per_page", String(PAGE_SIZE));
424
+ u.searchParams.set("include_totals", "false");
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 *]`);
430
+ }
431
+ u.searchParams.set("q", clauses.join(" AND "));
432
+ return u.toString();
433
+ }
434
+ buildDailyStatsUrl(options) {
435
+ const lookback = this.settings.statsLookbackDays ?? DEFAULT_STATS_LOOKBACK_DAYS;
436
+ const to = /* @__PURE__ */ new Date();
437
+ let from = new Date(to.getTime() - (lookback - 1) * 24 * 60 * 60 * 1e3);
438
+ if (options.since) {
439
+ const sinceMs = Date.parse(options.since);
440
+ if (Number.isFinite(sinceMs)) {
441
+ const sinceDate = new Date(sinceMs);
442
+ if (sinceDate.getTime() > from.getTime()) {
443
+ from = sinceDate;
444
+ }
445
+ }
446
+ }
447
+ const u = new URL(`${this.baseUrl()}/api/v2/stats/daily`);
448
+ u.searchParams.set("from", yyyymmdd(from));
449
+ u.searchParams.set("to", yyyymmdd(to));
450
+ return u.toString();
451
+ }
452
+ async fetchUsersPage(page, options, signal) {
453
+ const pageNum = this.parsePageCursor(page);
454
+ const url = this.buildUsersUrl(pageNum, options);
455
+ const res = await this.apiGet(url, "users", signal);
456
+ const users = res.body.users;
457
+ const length = res.body.length ?? users.length;
458
+ const nextPage = pageNum + 1;
459
+ const hasMore = length >= PAGE_SIZE && nextPage < MAX_USER_PAGES;
460
+ return { items: users, next: hasMore ? String(nextPage) : null };
461
+ }
462
+ async fetchLogsPage(page, options, signal) {
463
+ const pageNum = this.parsePageCursor(page);
464
+ const url = this.buildLogsUrl(pageNum, options);
465
+ const res = await this.apiGet(url, "logs", signal);
466
+ const logs = res.body;
467
+ const nextPage = pageNum + 1;
468
+ const hasMore = logs.length >= PAGE_SIZE && nextPage < MAX_USER_PAGES;
469
+ return { items: logs, next: hasMore ? String(nextPage) : null };
470
+ }
471
+ async fetchDailyStats(page, options, signal) {
472
+ if (page !== null) {
473
+ return { items: [], next: null };
474
+ }
475
+ const url = this.buildDailyStatsUrl(options);
476
+ const res = await this.apiGet(
477
+ url,
478
+ "daily_stats",
479
+ signal
480
+ );
481
+ return { items: res.body, next: null };
482
+ }
483
+ async writeUsers(storage, items) {
484
+ for (const u of items) {
485
+ const lastLoginMs = parseEpoch(u.last_login ?? null, "iso");
486
+ const createdMs = parseEpoch(u.created_at ?? null, "iso");
487
+ const updatedMs = parseEpoch(u.updated_at ?? null, "iso");
488
+ await storage.entity({
489
+ type: USER_ENTITY,
490
+ id: u.user_id,
491
+ attributes: {
492
+ email: u.email ?? null,
493
+ identityProvider: primaryIdentityProvider(u),
494
+ lastLogin: lastLoginMs,
495
+ loginsCount: u.logins_count ?? null,
496
+ blocked: u.blocked ?? false,
497
+ createdAt: createdMs
498
+ },
499
+ updated_at: updatedMs ?? createdMs ?? 0
500
+ });
501
+ }
502
+ }
503
+ async writeLogs(storage, items) {
504
+ for (const log of items) {
505
+ const ts = parseEpoch(log.date, "iso");
506
+ if (ts === null) {
507
+ continue;
508
+ }
509
+ if (!isLogEventType(log.type)) {
510
+ continue;
511
+ }
512
+ await storage.event({
513
+ name: LOGIN_EVENT,
514
+ start_ts: ts,
515
+ end_ts: null,
516
+ attributes: {
517
+ logId: log._id,
518
+ type: log.type,
519
+ userId: log.user_id ?? null,
520
+ ip: log.ip ?? null,
521
+ connection: log.connection ?? null,
522
+ strategy: log.strategy ?? null
523
+ }
524
+ });
525
+ }
526
+ }
527
+ async writeDailyStats(storage, items) {
528
+ const samples = [];
529
+ for (const stat of items) {
530
+ const ts = parseEpoch(stat.date, "iso");
531
+ if (ts === null) {
532
+ continue;
533
+ }
534
+ if (typeof stat.logins === "number" && Number.isFinite(stat.logins)) {
535
+ samples.push({
536
+ name: DAILY_METRIC,
537
+ ts,
538
+ value: stat.logins,
539
+ attributes: { kind: "logins" }
540
+ });
541
+ }
542
+ if (typeof stat.signups === "number" && Number.isFinite(stat.signups)) {
543
+ samples.push({
544
+ name: DAILY_METRIC,
545
+ ts,
546
+ value: stat.signups,
547
+ attributes: { kind: "signups" }
548
+ });
549
+ }
550
+ }
551
+ if (samples.length > 0) {
552
+ await storage.metrics(samples, { names: [DAILY_METRIC] });
553
+ }
554
+ }
555
+ async writePhase(storage, phase, items) {
556
+ switch (phase) {
557
+ case "users":
558
+ return this.writeUsers(storage, items);
559
+ case "login_events":
560
+ return this.writeLogs(storage, items);
561
+ case "daily_active_users":
562
+ return this.writeDailyStats(storage, items);
563
+ }
564
+ }
565
+ async clearScopeOnFirstPage(storage, phase, isFull) {
566
+ if (!isFull) {
567
+ return;
568
+ }
569
+ switch (phase) {
570
+ case "users":
571
+ await storage.entities([], { types: [USER_ENTITY] });
572
+ return;
573
+ case "login_events":
574
+ await storage.events([], { names: [LOGIN_EVENT] });
575
+ return;
576
+ case "daily_active_users":
577
+ await storage.metrics([], { names: [DAILY_METRIC] });
578
+ return;
579
+ }
580
+ }
581
+ resolveCursor(cursor) {
582
+ return isAuth0SyncCursor(cursor) ? cursor : void 0;
583
+ }
584
+ async sync(options, storage, signal) {
585
+ const cursor = this.resolveCursor(options.cursor);
586
+ const isFull = options.mode === "full";
587
+ const phases = selectActivePhases(
588
+ (r) => r,
589
+ PHASE_ORDER,
590
+ this.settings.resources
591
+ );
592
+ return paginateChunked({
593
+ phases,
594
+ cursor,
595
+ signal,
596
+ logger: this.logger,
597
+ fetchPage: async (phase, page, sig) => {
598
+ switch (phase) {
599
+ case "users":
600
+ return this.fetchUsersPage(page, options, sig);
601
+ case "login_events":
602
+ return this.fetchLogsPage(page, options, sig);
603
+ case "daily_active_users":
604
+ return this.fetchDailyStats(page, options, sig);
605
+ }
606
+ },
607
+ writeBatch: async (phase, items, page) => {
608
+ if (page === null) {
609
+ await this.clearScopeOnFirstPage(storage, phase, isFull);
610
+ }
611
+ await this.writePhase(storage, phase, items);
612
+ }
613
+ });
614
+ }
615
+ };
616
+
617
+ // src/index.ts
618
+ var index_default = Auth0Connector;
619
+ export {
620
+ Auth0Connector,
621
+ configFields,
622
+ index_default as default,
623
+ doc,
624
+ id,
625
+ auth0Resources as resources
626
+ };
627
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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,EAAE,WAAW,SAAS,IA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AM,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"]}
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@rawdash/connector-auth0",
3
+ "version": "0.0.1",
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
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/rawdash/rawdash.git",
11
+ "directory": "packages/connectors/auth0"
12
+ },
13
+ "files": [
14
+ "dist",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "exports": {
19
+ ".": {
20
+ "@rawdash/source": "./src/index.ts",
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "scripts": {
26
+ "build": "tsup",
27
+ "typecheck": "tsc --noEmit",
28
+ "lint": "eslint src",
29
+ "test": "vitest run"
30
+ },
31
+ "dependencies": {
32
+ "@rawdash/core": "workspace:*",
33
+ "zod": "^4.4.3"
34
+ },
35
+ "devDependencies": {
36
+ "@rawdash/connector-shared": "workspace:*",
37
+ "@rawdash/connector-test-utils": "workspace:*",
38
+ "fast-check": "^4.8.0",
39
+ "tsup": "^8.0.0",
40
+ "typescript": "^5.7.2",
41
+ "vitest": "^4.1.4"
42
+ }
43
+ }