@niledatabase/server 5.0.0-alpha.3 → 5.0.0-alpha.30

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/dist/index.d.mts CHANGED
@@ -1,32 +1,38 @@
1
1
  import pg, { PoolConfig, PoolClient } from 'pg';
2
2
 
3
+ type LogFunction = (message: string | unknown, meta?: Record<string, unknown>) => void;
4
+ type Loggable = {
5
+ info: LogFunction;
6
+ debug: LogFunction;
7
+ warn: LogFunction;
8
+ error: LogFunction;
9
+ silly: LogFunction;
10
+ };
11
+ type LogReturn = (prefixes?: string | string[]) => Loggable;
12
+
13
+ type ConfigurablePaths = {
14
+ get: string[];
15
+ post: string[];
16
+ delete: string[];
17
+ put: string[];
18
+ };
19
+ type ExtensionReturns = void | Response | Request | ExtensionState;
20
+ type ExtensionCtx = {
21
+ runExtensions: <T = ExtensionReturns>(toRun: ExtensionState, config: Config, params?: any, _init?: RequestInit & {
22
+ request: Request;
23
+ }) => Promise<T>;
24
+ };
25
+ type ConfigConstructor = NileConfig & {
26
+ extensionCtx?: ExtensionCtx;
27
+ };
3
28
  declare class Config {
4
29
  routes: Routes;
5
- handlers: {
6
- GET: (req: Request) => Promise<void | Response>;
7
- POST: (req: Request) => Promise<void | Response>;
8
- DELETE: (req: Request) => Promise<void | Response>;
9
- PUT: (req: Request) => Promise<void | Response>;
10
- };
11
- paths: {
12
- get: string[];
13
- post: string[];
14
- delete: string[];
15
- put: string[];
16
- };
17
- logger?: LoggerType;
18
- /**
19
- * Stores the set tenant id from Server for use in sub classes
20
- */
21
- tenantId: string | null | undefined;
22
- /**
23
- * Stores the set user id from Server for use in sub classes
24
- */
25
- userId: string | null | undefined;
26
- /**
27
- * Stores the headers to be used in `fetch` calls
28
- */
29
- headers: Headers;
30
+ handlers: RouteFunctions;
31
+ paths: ConfigurablePaths;
32
+ extensionCtx: ExtensionCtx;
33
+ extensions?: Extension[];
34
+ logger: LogReturn;
35
+ context: PartialContext;
30
36
  /**
31
37
  * The nile-auth url
32
38
  */
@@ -47,7 +53,7 @@ declare class Config {
47
53
  */
48
54
  routePrefix: string;
49
55
  db: NilePoolConfig;
50
- constructor(config?: NileConfig, logger?: string);
56
+ constructor(config?: ConfigConstructor);
51
57
  }
52
58
 
53
59
  type Routes = {
@@ -70,193 +76,10 @@ type Routes = {
70
76
  PASSWORD_RESET: string;
71
77
  LOG: string;
72
78
  VERIFY_EMAIL: string;
79
+ INVITES: string;
80
+ INVITE: string;
73
81
  };
74
82
 
75
- type Opts = {
76
- basePath?: string;
77
- fetch?: typeof fetch;
78
- };
79
- type NilePoolConfig = PoolConfig & {
80
- afterCreate?: AfterCreate;
81
- };
82
- type LoggerType = {
83
- info?: (args: unknown | unknown[]) => void;
84
- warn?: (args: unknown | unknown[]) => void;
85
- error?: (args: unknown | unknown[]) => void;
86
- debug?: (args: unknown | unknown[]) => void;
87
- };
88
- type NileConfig = {
89
- /**
90
- * The specific database id. Either passed in or figured out by NILEDB_API_URL
91
- * process.env.NILEDB_ID
92
- */
93
- databaseId?: string;
94
- /**
95
- * The user UUID to the database
96
- * process.env.NILEDB_USER
97
- */
98
- user?: string;
99
- /**
100
- * The password UUID to the database
101
- * process.env.NILEDB_PASSWORD
102
- */
103
- password?: string;
104
- /**
105
- * The name of the database. Automatically obtained from NILEDB_POSTGRES_URL
106
- * process.env.NILEDB_NAME
107
- */
108
- databaseName?: string;
109
- /**
110
- * A tenant id. Scopes requests to a specific tenant, both API and DB
111
- * process.env.NILEDB_TENANT
112
- */
113
- tenantId?: string | null | undefined;
114
- /**
115
- * A user id. Possibly not the logged in user, used for setting database context (nile.user_id)
116
- * Generally speaking, this wouldn't be used for authentication, and in some cases simply won't do anything on some endpoints
117
- */
118
- userId?: string | null | undefined;
119
- /**
120
- * Shows a bunch of logging on the server side to see what's being done between the sdk and nile-auth
121
- */
122
- debug?: boolean;
123
- /**
124
- * DB configuration overrides. Environment variables are the way to go, but maybe you need something more
125
- */
126
- db?: NilePoolConfig;
127
- /**
128
- * Some kind of logger if you want to send to an external service
129
- */
130
- logger?: LoggerType;
131
- /**
132
- * The configuration value that maps to `NILEDB_API_URL` - its going to be nile-auth (or similar service)
133
- */
134
- apiUrl?: string | undefined;
135
- /**
136
- * Ignore client callbackUrls by setting this.
137
- * You can force the callback URL server side to be sure nile-auth redirects to whatever location.
138
- */
139
- callbackUrl?: string | undefined;
140
- /**
141
- * Need to override some routes? Change it here
142
- */
143
- routes?: Partial<Routes>;
144
- /**
145
- * don't like the default `/api`? change it here
146
- */
147
- routePrefix?: string | undefined;
148
- /**
149
- * In some cases, you may want to force secure cookies.
150
- * The SDK handles this for you, but might be necessary in some firewall / internal cases
151
- * Defaults to true if you're in production
152
- */
153
- secureCookies?: boolean;
154
- /**
155
- * The origin for the requests.
156
- * Allows the setting of the callback origin to a random FE
157
- * eg FE localhost:3001 -> BE: localhost:5432 would set to localhost:3001 to be sure nile-auth uses that.
158
- * In full stack cases, will just be the `host` header of the incoming request, which is used by default
159
- * It is also important to set this when dealing with secure cookies. Calling via server side needs to know if TLS is being used so that nile-auth knows which cookies to be sent.
160
- */
161
- origin?: null | undefined | string;
162
- /**
163
- * Set the headers to use in API requests.
164
- * The `cookie` would be expected if you are setting this, else most calls will be unauthorized
165
- */
166
- headers?: null | Headers | Record<string, string>;
167
- };
168
- type NileDb = NilePoolConfig & {
169
- tenantId?: string;
170
- };
171
- type AfterCreate = (conn: PoolClient, done: (err: null | Error, conn: PoolClient) => void) => void;
172
- interface NileBody<R, B> {
173
- readonly body: ReadableStream<Uint8Array> | null | B;
174
- readonly bodyUsed: boolean;
175
- arrayBuffer(): Promise<ArrayBuffer>;
176
- blob(): Promise<Blob>;
177
- formData(): Promise<FormData>;
178
- json(): Promise<R>;
179
- text(): Promise<string>;
180
- }
181
- interface NResponse<T> extends NileBody<T, any> {
182
- readonly headers: Headers;
183
- readonly ok: boolean;
184
- readonly redirected: boolean;
185
- readonly status: number;
186
- readonly statusText: string;
187
- readonly type: ResponseType;
188
- readonly url: string;
189
- clone(): Response;
190
- }
191
- interface NRequest<T> extends NileBody<any, T> {
192
- /** Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching. */
193
- readonly cache: RequestCache;
194
- /** Returns the credentials mode associated with request, which is a string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. */
195
- readonly credentials: RequestCredentials;
196
- /** Returns the kind of resource requested by request, e.g., "document" or "script". */
197
- readonly destination: RequestDestination;
198
- /** Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. */
199
- readonly headers: Headers;
200
- /** Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] */
201
- readonly integrity: string;
202
- /** Returns a boolean indicating whether or not request can outlive the global in which it was created. */
203
- readonly keepalive: boolean;
204
- /** Returns request's HTTP method, which is "GET" by default. */
205
- readonly method: string;
206
- /** Returns the mode associated with request, which is a string indicating whether the request will use CORS, or will be restricted to same-origin URLs. */
207
- readonly mode: RequestMode;
208
- /** Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. */
209
- readonly redirect: RequestRedirect;
210
- /** Returns the referrer of request. Its value can be a same-origin URL if explicitly set in init, the empty string to indicate no referrer, and "about:client" when defaulting to the global's default. This is used during fetching to determine the value of the `Referer` header of the request being made. */
211
- readonly referrer: string;
212
- /** Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer. */
213
- readonly referrerPolicy: ReferrerPolicy;
214
- /** Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. */
215
- readonly signal: AbortSignal;
216
- /** Returns the URL of request as a string. */
217
- readonly url: string;
218
- clone(): Request;
219
- }
220
- type NileRequest<T> = NRequest<T> | T;
221
- declare const APIErrorErrorCodeEnum: {
222
- readonly InternalError: "internal_error";
223
- readonly BadRequest: "bad_request";
224
- readonly EntityNotFound: "entity_not_found";
225
- readonly DuplicateEntity: "duplicate_entity";
226
- readonly InvalidCredentials: "invalid_credentials";
227
- readonly UnknownOidcProvider: "unknown_oidc_provider";
228
- readonly ProviderAlreadyExists: "provider_already_exists";
229
- readonly ProviderConfigError: "provider_config_error";
230
- readonly ProviderMismatch: "provider_mismatch";
231
- readonly ProviderUpdateError: "provider_update_error";
232
- readonly SessionStateMissing: "session_state_missing";
233
- readonly SessionStateMismatch: "session_state_mismatch";
234
- readonly OidcCodeMissing: "oidc_code_missing";
235
- };
236
- type APIErrorErrorCodeEnum = (typeof APIErrorErrorCodeEnum)[keyof typeof APIErrorErrorCodeEnum];
237
- interface APIError {
238
- [key: string]: any | any;
239
- /**
240
- *
241
- * @type {string}
242
- * @memberof APIError
243
- */
244
- errorCode: APIErrorErrorCodeEnum;
245
- /**
246
- *
247
- * @type {string}
248
- * @memberof APIError
249
- */
250
- message: string;
251
- /**
252
- *
253
- * @type {number}
254
- * @memberof APIError
255
- */
256
- statusCode: number;
257
- }
258
- type NileResponse<T> = Promise<T | NResponse<T & APIError>>;
259
-
260
83
  interface CreateBasicUserRequest {
261
84
  email: string;
262
85
  password: string;
@@ -304,56 +127,90 @@ interface User {
304
127
  tenants: string[];
305
128
  }
306
129
 
307
- type Tenant = {
308
- id: string;
309
- name: string;
310
- };
311
-
312
- type ProviderName = 'discord' | 'github' | 'google' | 'hubspot' | 'linkedin' | 'slack' | 'twitter' | 'email' | 'credentials' | 'azure';
313
- type Providers = {
314
- [providerName in ProviderName]: Provider;
315
- };
316
- type Provider = {
317
- id: string;
318
- name: string;
319
- type: string;
320
- signinUrl: string;
321
- callbackUrl: string;
322
- };
323
- type JWT = {
324
- email: string;
325
- sub: string;
326
- id: string;
327
- iat: number;
328
- exp: number;
329
- jti: string;
330
- };
331
- type ActiveSession = {
332
- id: string;
333
- email: string;
334
- expires: string;
335
- user?: {
336
- id: string;
337
- name: string;
338
- image: string;
339
- email: string;
340
- emailVerified: void | Date;
341
- };
342
- };
343
-
130
+ /**
131
+ * Convenience wrapper around the user endpoints.
132
+ *
133
+ * Requests are issued via {@link fetchMe} against `/api/me`. The Swagger
134
+ * definitions for these APIs live in
135
+ * `packages/server/src/api/routes/me/index.ts`.
136
+ */
344
137
  declare class Users {
345
138
  #private;
139
+ /**
140
+ * Create a new Users helper.
141
+ * @param config - The configuration used for requests.
142
+ */
346
143
  constructor(config: Config);
144
+ /**
145
+ * Update the current user via `PUT /api/me`.
146
+ *
147
+ * The OpenAPI description for this endpoint can be found in
148
+ * `packages/server/src/api/routes/me/index.ts` under `updateSelf`.
149
+ *
150
+ * @param req - Partial user fields to send.
151
+ * @param [rawResponse] - When `true`, return the raw {@link Response}.
152
+ */
347
153
  updateSelf<T = User[] | Response>(req: Partial<Omit<User, 'email' | 'tenants' | 'created' | 'updated' | 'emailVerified'> & {
348
154
  emailVerified: boolean;
349
155
  }>, rawResponse?: boolean): Promise<T>;
156
+ /**
157
+ * Remove the current user using `DELETE /api/me`.
158
+ *
159
+ * After the request the authentication headers are cleared with
160
+ * {@link updateHeaders}. The OpenAPI docs for this route are in
161
+ * `packages/server/src/api/routes/me/index.ts` under `removeSelf`.
162
+ */
350
163
  removeSelf(): Promise<Response>;
351
- getSelf<T = User | Response>(): Promise<T>;
352
- getSelf(rawResponse?: true): Promise<Response>;
353
- verifySelf<T = Response | void>(): Promise<T>;
354
- verifySelf(rawResponse?: true): Promise<Response>;
164
+ /**
165
+ * Retrieve the current user with `GET /api/me`.
166
+ *
167
+ * OpenAPI for this endpoint resides in
168
+ * `packages/server/src/api/routes/me/index.ts` (`getSelf`).
169
+ *
170
+ * @param [rawResponse] - When `true` return the raw {@link Response}.
171
+ */
172
+ getSelf<T = User | Response>(rawResponse?: false): Promise<T>;
173
+ getSelf(rawResponse: true): Promise<Response>;
174
+ /**
175
+ * Initiate an email verification flow.
176
+ *
177
+ * The current user is fetched and then `/auth/verify-email` is called.
178
+ * In development or when `bypassEmail` is set, the user's
179
+ * `emailVerified` field is updated instead of sending an email.
180
+ * See `packages/server/src/api/routes/auth/verify-email.ts` for the
181
+ * underlying request.
182
+ *
183
+ * @param [options] - Flags controlling bypass behaviour and callback URL.
184
+ * @param [rawResponse] - When `true` return the raw {@link Response}.
185
+ */
186
+ verifySelf<T = void>(): Promise<T>;
187
+ verifySelf(rawResponse: true): Promise<Response>;
188
+ verifySelf<T = Response | User>(options: {
189
+ bypassEmail?: boolean;
190
+ callbackUrl?: string;
191
+ }, rawResponse?: true): Promise<T>;
355
192
  }
356
193
 
194
+ type Tenant = {
195
+ id: string;
196
+ name: string;
197
+ };
198
+ type Invite = {
199
+ id: string;
200
+ tenant_id: string;
201
+ token: string;
202
+ identifier: string;
203
+ roles: null | string;
204
+ created_by: string;
205
+ expires: Date;
206
+ };
207
+
208
+ /**
209
+ * Convenience wrapper around the tenant endpoints. These methods call
210
+ * the `fetch*` helpers in `packages/server/src/api/routes/tenants` which
211
+ * in turn hit routes such as `/api/tenants` and `/api/tenants/{tenantId}`.
212
+ * See those files for the Swagger definitions.
213
+ */
357
214
  type ReqContext = {
358
215
  userId?: string;
359
216
  tenantId?: string;
@@ -364,106 +221,301 @@ type JoinTenantRequest = string | ReqContext | {
364
221
  declare class Tenants {
365
222
  #private;
366
223
  constructor(config: Config);
224
+ create(name: string, rawResponse: true): Promise<Response>;
367
225
  create<T = Tenant | Response>(name: string, rawResponse?: boolean): Promise<T>;
368
226
  create<T = Tenant | Response>(payload: {
369
227
  name: string;
370
228
  id?: string;
371
229
  }, rawResponse?: boolean): Promise<T>;
230
+ /**
231
+ * Delete a tenant using `DELETE /api/tenants/{tenantId}`.
232
+ * The OpenAPI operation is defined in
233
+ * `packages/server/src/api/routes/tenants/[tenantId]/DELETE.ts`.
234
+ */
372
235
  delete<T = Response>(id?: string): Promise<T>;
236
+ /**
237
+ * Delete a tenant using `DELETE /api/tenants/{tenantId}`.
238
+ * See `packages/server/src/api/routes/tenants/[tenantId]/DELETE.ts`.
239
+ */
373
240
  delete<T = Response>(payload: {
374
241
  id: string;
375
242
  }): Promise<T>;
243
+ get<T = Tenant | Response>(): Promise<T>;
376
244
  get<T = Tenant | Response>(id: string, rawResponse?: boolean): Promise<T>;
377
245
  get(rawResponse: true): Promise<Response>;
378
246
  get<T = Tenant | Response>(payload: {
379
247
  id: string;
380
248
  }, rawResponse?: boolean): Promise<T>;
381
249
  update(req: Partial<Tenant>, rawResponse: true): Promise<Response>;
250
+ /**
251
+ * Modify a tenant using `PUT /api/tenants/{tenantId}`.
252
+ *
253
+ * @param req - Tenant data to update. Can include an id.
254
+ * @param [rawResponse] - When true, return the raw {@link Response}.
255
+ */
382
256
  update<T = Tenant | Response | undefined>(req: Partial<Tenant>, rawResponse?: boolean): Promise<T>;
383
257
  list<T = Tenant[] | Response>(): Promise<T>;
384
258
  list(rawResponse: true): Promise<Response>;
259
+ /**
260
+ * Leave the current tenant using `DELETE /api/tenants/{tenantId}/users/{userId}`.
261
+ *
262
+ * @param [req] - Optionally specify the tenant id to leave.
263
+ */
385
264
  leaveTenant<T = Response>(req?: string | {
386
265
  tenantId: string;
387
266
  }): Promise<T>;
388
267
  addMember(req: JoinTenantRequest, rawResponse: true): Promise<Response>;
268
+ /**
269
+ * Add a user to a tenant via `PUT /api/tenants/{tenantId}/users/{userId}`.
270
+ *
271
+ * @param req - User and tenant identifiers or context.
272
+ * @param [rawResponse] - When true, return the raw {@link Response}.
273
+ */
389
274
  addMember<T = User | Response>(req: JoinTenantRequest, rawResponse?: boolean): Promise<T>;
275
+ /**
276
+ * Remove a user from a tenant with `DELETE /api/tenants/{tenantId}/users/{userId}`.
277
+ *
278
+ * @param req - User and tenant identifiers or context.
279
+ * @param [rawResponse] - When true, return the raw {@link Response}.
280
+ */
390
281
  removeMember(req: JoinTenantRequest, rawResponse?: boolean): Promise<Response>;
282
+ /**
283
+ * List users for a tenant via `GET /api/tenants/{tenantId}/users`.
284
+ *
285
+ * @param [req] - Tenant identifier or context.
286
+ * @param [rawResponse] - When true, return the raw {@link Response}.
287
+ */
391
288
  users<T = User[] | Response>(req?: boolean | {
392
289
  tenantId?: string;
393
290
  }, rawResponse?: boolean): Promise<T>;
394
291
  users(req: true): Promise<Response>;
292
+ /**
293
+ * List invites for the current tenant via `GET /api/tenants/{tenantId}/invites`.
294
+ */
295
+ invites<T = Invite[] | Response>(): Promise<T>;
296
+ /**
297
+ * Send an invitation via `POST /api/tenants/{tenantId}/invite`.
298
+ *
299
+ * @param req - Email and optional callback/redirect URLs.
300
+ * @param [rawResponse] - When true, return the raw {@link Response}.
301
+ */
302
+ invite<T = Response | Invite>(req: string | {
303
+ email: string;
304
+ callbackUrl?: string;
305
+ redirectUrl?: string;
306
+ }, rawResponse?: boolean): Promise<T>;
307
+ invite(req: string | {
308
+ email: string;
309
+ callbackUrl?: string;
310
+ redirectUrl?: string;
311
+ }, rawResponse: true): Promise<Response>;
312
+ /**
313
+ * Accept an invite using `PUT /api/tenants/{tenantId}/invite`.
314
+ *
315
+ * @param req - Identifier and token from the invite email.
316
+ * @param [rawResponse] - When true, return the raw {@link Response}.
317
+ */
318
+ acceptInvite<T = Response>(req?: {
319
+ identifier: string;
320
+ token: string;
321
+ callbackUrl?: string;
322
+ }, rawResponse?: boolean): Promise<T>;
323
+ /**
324
+ * Delete a pending invite using `DELETE /api/tenants/{tenantId}/invite/{inviteId}`.
325
+ *
326
+ * @param req - Identifier of the invite to remove.
327
+ */
328
+ deleteInvite<T = Response>(req: string | {
329
+ id: string;
330
+ }): Promise<T>;
395
331
  }
396
332
 
333
+ type ProviderName = 'discord' | 'github' | 'google' | 'hubspot' | 'linkedin' | 'slack' | 'twitter' | 'email' | 'credentials' | 'azure';
334
+ type Providers = {
335
+ [providerName in ProviderName]: Provider;
336
+ };
337
+ type Provider = {
338
+ id: string;
339
+ name: string;
340
+ type: string;
341
+ signinUrl: string;
342
+ callbackUrl: string;
343
+ };
344
+ type JWT = {
345
+ email: string;
346
+ sub: string;
347
+ id: string;
348
+ iat: number;
349
+ exp: number;
350
+ jti: string;
351
+ };
352
+ type ActiveSession = {
353
+ id: string;
354
+ email: string;
355
+ expires: string;
356
+ user?: {
357
+ id: string;
358
+ name: string;
359
+ image: string;
360
+ email: string;
361
+ emailVerified: void | Date;
362
+ };
363
+ };
364
+
397
365
  type SignUpPayload = {
398
366
  email: string;
399
367
  password: string;
400
368
  tenantId?: string;
401
369
  newTenantName?: string;
402
370
  };
371
+ /**
372
+ * Utility class that wraps the server side authentication endpoints.
373
+ *
374
+ * The methods in this class call the `fetch*` helpers which are generated
375
+ * from the OpenAPI specification. Those helpers interact with routes under
376
+ * the `/api/auth` prefix such as `/session`, `/signin`, `/signout` and others.
377
+ * By reusing them here we provide a higher level interface for frameworks to
378
+ * manage user authentication.
379
+ */
403
380
  declare class Auth {
404
381
  #private;
382
+ /**
383
+ * Create an Auth helper.
384
+ *
385
+ * @param config - runtime configuration used by the underlying fetch helpers
386
+ * such as `serverOrigin`, `routePrefix` and default headers.
387
+ */
405
388
  constructor(config: Config);
389
+ /**
390
+ * Retrieve the currently active session from the API.
391
+ *
392
+ * Internally this issues a `GET` request to `/api/auth/session` via
393
+ * {@link fetchSession}. If `rawResponse` is `true` the raw {@link Response}
394
+ * object is returned instead of the parsed JSON.
395
+ *
396
+ * @template T Return type for the parsed session.
397
+ * @param rawResponse - set to `true` to get the raw {@link Response} object.
398
+ */
406
399
  getSession<T = JWT | ActiveSession | undefined>(rawResponse?: false): Promise<T>;
407
400
  getSession(rawResponse: true): Promise<Response>;
401
+ /**
402
+ * Acquire a CSRF token for subsequent authenticated requests.
403
+ *
404
+ * Issues a `GET` to `/api/auth/csrf` via {@link obtainCsrf}. When the call
405
+ * succeeds the returned headers are merged into the current configuration so
406
+ * future requests include the appropriate cookies.
407
+ *
408
+ * @param rawResponse - when `true`, skip JSON parsing and return the raw
409
+ * {@link Response}.
410
+ */
408
411
  getCsrf<T = Response | JSON>(rawResponse?: false): Promise<T>;
409
412
  getCsrf(rawResponse: true): Promise<Response>;
413
+ /**
414
+ * List all configured authentication providers.
415
+ *
416
+ * This calls `/api/auth/providers` using {@link fetchProviders} to retrieve
417
+ * the available provider configuration. Providers are returned as an object
418
+ * keyed by provider name.
419
+ *
420
+ * @param rawResponse - when true, return the {@link Response} instead of the
421
+ * parsed JSON.
422
+ */
410
423
  listProviders(rawResponse: true): Promise<Response>;
411
424
  listProviders<T = {
412
425
  [key: string]: Provider;
413
426
  }>(rawResponse?: false): Promise<T>;
427
+ /**
428
+ * Sign the current user out by calling `/api/auth/signout`.
429
+ *
430
+ * The CSRF token is fetched automatically and the stored cookies are cleared
431
+ * from the internal configuration once the request completes.
432
+ */
414
433
  signOut(): Promise<Response>;
415
434
  /**
416
- * signUp only works with email + password
417
- * @param payload
418
- * @param rawResponse
435
+ * Create a new user account and start a session.
436
+ *
437
+ * This method posts to the `/api/signup` endpoint using
438
+ * {@link fetchSignUp}. Only the credential provider is supported; a valid
439
+ * email and password must be supplied. On success the returned session token
440
+ * is stored in the headers used for subsequent requests.
441
+ *
442
+ * @param payload - email and password along with optional tenant
443
+ * information.
444
+ * @param rawResponse - when `true` return the raw {@link Response} rather
445
+ * than the parsed {@link User} object.
419
446
  */
420
447
  signUp(payload: SignUpPayload, rawResponse: true): Promise<Response>;
421
448
  signUp<T = User | Response>(payload: SignUpPayload): Promise<T>;
449
+ /**
450
+ * Request a password reset email.
451
+ *
452
+ * Sends a `POST` to `/api/auth/password-reset` with the provided email and
453
+ * optional callback information. The endpoint responds with a redirect URL
454
+ * which is returned as a {@link Response} object.
455
+ */
422
456
  forgotPassword(req: {
423
457
  email: string;
424
458
  callbackUrl?: string;
425
459
  redirectUrl?: string;
426
460
  }): Promise<Response>;
461
+ /**
462
+ * Complete a password reset.
463
+ *
464
+ * This workflow expects a token obtained from {@link forgotPassword}. The
465
+ * function performs a POST/GET/PUT sequence against
466
+ * `/api/auth/password-reset` as described in the OpenAPI specification.
467
+ *
468
+ * @param req - either a {@link Request} with a JSON body or an object
469
+ * containing the necessary fields.
470
+ */
427
471
  resetPassword(req: Request | {
428
472
  email: string;
429
473
  password: string;
430
474
  callbackUrl?: string;
431
475
  redirectUrl?: string;
432
476
  }): Promise<Response>;
477
+ /**
478
+ * Low level helper used by {@link signIn} to complete provider flows.
479
+ *
480
+ * Depending on the provider this issues either a GET or POST request to
481
+ * `/api/auth/callback/{provider}` via {@link fetchCallback}.
482
+ */
433
483
  callback(provider: ProviderName, body?: string | Request): Promise<Response>;
434
484
  /**
435
- * The return value from this will be a redirect for the client
436
- * In most cases, you should forward the response directly to the client
437
- * @param payload
438
- * @param rawResponse
485
+ * Sign a user in with one of the configured providers.
486
+ *
487
+ * Internally this posts to `/api/auth/signin/{provider}` and follows the
488
+ * provider callback flow as documented in the OpenAPI spec. When using the
489
+ * credential provider an email and password must be supplied.
490
+ *
491
+ * @param payload - request body or credential object
492
+ * @param rawResponse - return the raw {@link Response} instead of parsed JSON
439
493
  */
440
494
  signIn<T = Response>(provider: ProviderName, payload?: Request | {
441
495
  email: string;
442
496
  password: string;
443
497
  }, rawResponse?: true): Promise<T>;
444
498
  }
499
+ /**
500
+ * Extract the CSRF cookie from a set of headers.
501
+ */
445
502
  declare function parseCSRF(headers?: Headers): string | undefined;
503
+ /**
504
+ * Extract the callback cookie from a set of headers.
505
+ */
446
506
  declare function parseCallback(headers?: Headers): string | undefined;
507
+ /**
508
+ * Extract the session token cookie from a set of headers.
509
+ */
447
510
  declare function parseToken(headers?: Headers): string | undefined;
448
-
449
- type CTXHandlerType = {
450
- GET: (req: Request) => Promise<{
451
- response: void | Response;
452
- nile: Server;
453
- }>;
454
- POST: (req: Request) => Promise<{
455
- response: void | Response;
456
- nile: Server;
457
- }>;
458
- DELETE: (req: Request) => Promise<{
459
- response: void | Response;
460
- nile: Server;
461
- }>;
462
- PUT: (req: Request) => Promise<{
463
- response: void | Response;
464
- nile: Server;
465
- }>;
466
- };
511
+ /**
512
+ * Internal helper for the password reset flow.
513
+ */
514
+ declare function parseResetToken(headers: Headers | void): string | void;
515
+ /**
516
+ * Extract the tenantId cookie from a set of headers.
517
+ */
518
+ declare function parseTenantId(headers?: Headers): string | null | undefined;
467
519
 
468
520
  declare class Server {
469
521
  #private;
@@ -474,40 +526,292 @@ declare class Server {
474
526
  get db(): pg.Pool & {
475
527
  clearConnections: () => void;
476
528
  };
529
+ get logger(): LogReturn;
530
+ get extensions(): {
531
+ remove: (id: string) => Promise<ExtensionResult<any>[] | undefined>;
532
+ add: (extension: Extension) => void;
533
+ };
534
+ get handlers(): NileHandlers;
535
+ get paths(): ConfigurablePaths;
536
+ set paths(paths: ConfigurablePaths);
537
+ /** Allows setting of context outside of the request lifecycle
538
+ * Basically means you want to disregard cookies and do everything manually
539
+ * If we elect to DDL, we don't want to use tenant id or user id, so remove those.
540
+ */
541
+ withContext(context?: PartialContext): Promise<this>;
542
+ withContext<T>(context: PartialContext, fn: (sdk: this) => Promise<T>): Promise<T>;
477
543
  /**
478
- * A convenience function that applies a config and ensures whatever was passed is set properly
544
+ * Creates a context without a user id and a tenant id, but keeps the headers around for auth at least.
479
545
  */
480
- getInstance<T = Request | Headers | Record<string, string>>(config: NileConfig, req?: T): Server;
481
- getPaths(): {
482
- get: string[];
483
- post: string[];
484
- delete: string[];
485
- put: string[];
486
- };
487
- get handlers(): {
488
- GET: (req: Request) => Promise<void | Response>;
489
- POST: (req: Request) => Promise<void | Response>;
490
- DELETE: (req: Request) => Promise<void | Response>;
491
- PUT: (req: Request) => Promise<void | Response>;
492
- withContext: CTXHandlerType;
493
- };
546
+ noContext(): Promise<this>;
547
+ noContext<T>(fn: (sdk: this) => Promise<T>): Promise<T>;
494
548
  /**
495
- * Allow the setting of headers from a req or header object.
496
- * Makes it possible to handle REST requests easily
497
- * Also makes it easy to set user + tenant in some way
498
- * @param req
499
- * @returns undefined
549
+ *
550
+ * @returns the last used (basically global) context object, useful for debugging or making your own context
500
551
  */
501
- setContext(req: Request | Headers | Record<string, string> | unknown | {
502
- tenantId?: string;
503
- userId?: string;
504
- }): void;
505
- getContext(): {
506
- headers: Headers | undefined;
507
- userId: string | null | undefined;
508
- tenantId: string | null | undefined;
552
+ getContext(): Context;
553
+ }
554
+ declare function create<T = Server>(config?: NileConfig): T;
555
+
556
+ type Opts = {
557
+ basePath?: string;
558
+ fetch?: typeof fetch;
559
+ };
560
+ type Context = {
561
+ headers: Headers;
562
+ tenantId: string | undefined | null;
563
+ userId: string | undefined | null;
564
+ preserveHeaders: boolean;
565
+ };
566
+ type PartialContext = {
567
+ headers?: null | Headers;
568
+ tenantId?: string | undefined | null;
569
+ userId?: string | undefined | null;
570
+ preserveHeaders?: boolean;
571
+ };
572
+ type CTX = {
573
+ run: <T>(ctx: Partial<Context>, fn: () => T) => T;
574
+ get: () => Context;
575
+ set: (partial: Partial<PartialContext>) => void;
576
+ getLastUsed: () => Context;
577
+ };
578
+ type Any = any;
579
+ type ExtensionResult<TParams> = {
580
+ id: string;
581
+ withContext?: (ctx: CTX) => Promise<void>;
582
+ onRequest?: (params: TParams, ctx: CTX) => void | Promise<void | RequestInit>;
583
+ onResponse?: (params: TParams, ctx: CTX) => void | Promise<void>;
584
+ onHandleRequest?: (params?: TParams) => RouteReturn | Promise<RouteReturn>;
585
+ onConfigure?: (params?: TParams) => void;
586
+ replace?: {
587
+ handlers: (handlers: NileHandlers) => Any;
509
588
  };
589
+ };
590
+ type NileHandlers = RouteFunctions & {
591
+ withContext: CTXHandlerType;
592
+ };
593
+ type Extension<TParams = Any> = (instance: Server) => ExtensionResult<TParams>;
594
+ declare enum ExtensionState {
595
+ onHandleRequest = "onHandleRequest",
596
+ onRequest = "onRequest",
597
+ onResponse = "onResponse",
598
+ withContext = "withContext"
510
599
  }
511
- declare function create(config?: NileConfig): Server;
600
+ type NilePoolConfig = PoolConfig & {
601
+ afterCreate?: AfterCreate;
602
+ };
603
+ type LoggerType = {
604
+ info: (args: unknown | unknown[]) => void;
605
+ warn: (args: unknown | unknown[]) => void;
606
+ error: (args: unknown | unknown[]) => void;
607
+ debug: (args: unknown | unknown[]) => void;
608
+ };
609
+ /**
610
+ * Configuration options used by the {@link Server} class.
611
+ * Most values can be provided via environment variables if not set here.
612
+ */
613
+ type NileConfig = {
614
+ /**
615
+ * Unique ID of the database.
616
+ * If omitted, the value is derived from `NILEDB_API_URL`.
617
+ * Environment variable: `NILEDB_ID`.
618
+ */
619
+ databaseId?: string;
620
+ /**
621
+ * Database user used for authentication.
622
+ * Environment variable: `NILEDB_USER`.
623
+ */
624
+ user?: string;
625
+ /**
626
+ * Password for the configured user.
627
+ * Environment variable: `NILEDB_PASSWORD`.
628
+ */
629
+ password?: string;
630
+ /**
631
+ * Database name. Defaults to the name parsed from
632
+ * `NILEDB_POSTGRES_URL` when not provided.
633
+ * Environment variable: `NILEDB_NAME`.
634
+ */
635
+ databaseName?: string;
636
+ /**
637
+ * Tenant context used for scoping API and DB calls.
638
+ * Environment variable: `NILEDB_TENANT`.
639
+ */
640
+ tenantId?: string | null | undefined;
641
+ /**
642
+ * Optional user identifier to apply when interacting with the database.
643
+ * In most cases nile-auth injects the logged in user automatically so this
644
+ * value rarely needs to be specified directly. It can be useful when
645
+ * performing administrative actions on behalf of another user.
646
+ */
647
+ userId?: string | null | undefined;
648
+ /** Enable verbose logging of SDK behaviour. */
649
+ debug?: boolean;
650
+ /**
651
+ * Optional Postgres connection configuration.
652
+ * Environment variables will be used for any values not set here.
653
+ */
654
+ db?: NilePoolConfig;
655
+ /** Custom logger implementation. */
656
+ logger?: LogReturn;
657
+ /**
658
+ * Base URL for nile-auth requests.
659
+ * Environment variable: `NILEDB_API_URL`.
660
+ */
661
+ apiUrl?: string | undefined;
662
+ /**
663
+ * Override the client provided callback URL during authentication.
664
+ * Environment variable: `NILEDB_CALLBACK_URL`.
665
+ */
666
+ callbackUrl?: string | undefined;
667
+ /** Override default API routes. */
668
+ routes?: Partial<Routes>;
669
+ /** Prefix applied to all generated routes. */
670
+ routePrefix?: string | undefined;
671
+ /**
672
+ * Force usage of secure cookies when communicating with nile-auth.
673
+ * Defaults to `true` when `NODE_ENV` is `production`.
674
+ * Environment variable: `NILEDB_SECURECOOKIES`.
675
+ */
676
+ secureCookies?: boolean;
677
+ /**
678
+ * Origin for requests made to nile-auth. This controls where users are
679
+ * redirected after authentication. For single-page apps running on a
680
+ * different port than the API, set this to the front-end origin
681
+ * (e.g. `http://localhost:3001`). In a full-stack setup the value defaults
682
+ * to the `host` header of the incoming request. When using secure cookies on
683
+ * server-to-server calls, explicitly setting the origin ensures nile-auth
684
+ * knows whether TLS is being used and which cookies to send.
685
+ */
686
+ origin?: null | undefined | string;
687
+ /**
688
+ * Additional headers sent with every API request.
689
+ * Include a `cookie` header to forward session information.
690
+ */
691
+ headers?: null | Headers | Record<string, string>;
692
+ /** Hooks executed before and after each request. */
693
+ extensions?: Extension[];
694
+ /**
695
+ * Preserve incoming request headers when running extensions.
696
+ */
697
+ preserveHeaders?: boolean;
698
+ };
699
+ type NileDb = NilePoolConfig & {
700
+ tenantId?: string;
701
+ };
702
+ type AfterCreate = (conn: PoolClient, done: (err: null | Error, conn: PoolClient) => void) => void;
703
+ interface NileBody<R, B> {
704
+ readonly body: ReadableStream<Uint8Array> | null | B;
705
+ readonly bodyUsed: boolean;
706
+ arrayBuffer(): Promise<ArrayBuffer>;
707
+ blob(): Promise<Blob>;
708
+ formData(): Promise<FormData>;
709
+ json(): Promise<R>;
710
+ text(): Promise<string>;
711
+ }
712
+ interface NResponse<T> extends NileBody<T, any> {
713
+ readonly headers: Headers;
714
+ readonly ok: boolean;
715
+ readonly redirected: boolean;
716
+ readonly status: number;
717
+ readonly statusText: string;
718
+ readonly type: ResponseType;
719
+ readonly url: string;
720
+ clone(): Response;
721
+ }
722
+ interface NRequest<T> extends NileBody<any, T> {
723
+ /** Returns the cache mode associated with request, which is a string indicating how the request will interact with the browser's cache when fetching. */
724
+ readonly cache: RequestCache;
725
+ /** Returns the credentials mode associated with request, which is a string indicating whether credentials will be sent with the request always, never, or only when sent to a same-origin URL. */
726
+ readonly credentials: RequestCredentials;
727
+ /** Returns the kind of resource requested by request, e.g., "document" or "script". */
728
+ readonly destination: RequestDestination;
729
+ /** Returns a Headers object consisting of the headers associated with request. Note that headers added in the network layer by the user agent will not be accounted for in this object, e.g., the "Host" header. */
730
+ readonly headers: Headers;
731
+ /** Returns request's subresource integrity metadata, which is a cryptographic hash of the resource being fetched. Its value consists of multiple hashes separated by whitespace. [SRI] */
732
+ readonly integrity: string;
733
+ /** Returns a boolean indicating whether or not request can outlive the global in which it was created. */
734
+ readonly keepalive: boolean;
735
+ /** Returns request's HTTP method, which is "GET" by default. */
736
+ readonly method: string;
737
+ /** Returns the mode associated with request, which is a string indicating whether the request will use CORS, or will be restricted to same-origin URLs. */
738
+ readonly mode: RequestMode;
739
+ /** Returns the redirect mode associated with request, which is a string indicating how redirects for the request will be handled during fetching. A request will follow redirects by default. */
740
+ readonly redirect: RequestRedirect;
741
+ /** Returns the referrer of request. Its value can be a same-origin URL if explicitly set in init, the empty string to indicate no referrer, and "about:client" when defaulting to the global's default. This is used during fetching to determine the value of the `Referer` header of the request being made. */
742
+ readonly referrer: string;
743
+ /** Returns the referrer policy associated with request. This is used during fetching to compute the value of the request's referrer. */
744
+ readonly referrerPolicy: ReferrerPolicy;
745
+ /** Returns the signal associated with request, which is an AbortSignal object indicating whether or not request has been aborted, and its abort event handler. */
746
+ readonly signal: AbortSignal;
747
+ /** Returns the URL of request as a string. */
748
+ readonly url: string;
749
+ clone(): Request;
750
+ }
751
+ type NileRequest<T> = NRequest<T> | T;
752
+ declare const APIErrorErrorCodeEnum: {
753
+ readonly InternalError: "internal_error";
754
+ readonly BadRequest: "bad_request";
755
+ readonly EntityNotFound: "entity_not_found";
756
+ readonly DuplicateEntity: "duplicate_entity";
757
+ readonly InvalidCredentials: "invalid_credentials";
758
+ readonly UnknownOidcProvider: "unknown_oidc_provider";
759
+ readonly ProviderAlreadyExists: "provider_already_exists";
760
+ readonly ProviderConfigError: "provider_config_error";
761
+ readonly ProviderMismatch: "provider_mismatch";
762
+ readonly ProviderUpdateError: "provider_update_error";
763
+ readonly SessionStateMissing: "session_state_missing";
764
+ readonly SessionStateMismatch: "session_state_mismatch";
765
+ readonly OidcCodeMissing: "oidc_code_missing";
766
+ };
767
+ type APIErrorErrorCodeEnum = (typeof APIErrorErrorCodeEnum)[keyof typeof APIErrorErrorCodeEnum];
768
+ interface APIError {
769
+ [key: string]: any | any;
770
+ /**
771
+ *
772
+ * @type {string}
773
+ * @memberof APIError
774
+ */
775
+ errorCode: APIErrorErrorCodeEnum;
776
+ /**
777
+ *
778
+ * @type {string}
779
+ * @memberof APIError
780
+ */
781
+ message: string;
782
+ /**
783
+ *
784
+ * @type {number}
785
+ * @memberof APIError
786
+ */
787
+ statusCode: number;
788
+ }
789
+ type NileResponse<T> = Promise<T | NResponse<T & APIError>>;
790
+ type ExtensionConfig = {
791
+ disableExtensions: string[];
792
+ };
793
+ type DefaultRouteReturn = Request | Response | ExtensionState;
794
+ type RouteReturn<T = unknown> = void | T | Promise<void | T>;
795
+ type RouteFunctions<T = DefaultRouteReturn> = {
796
+ GET: (req: Request, config?: ExtensionConfig, ...args: unknown[]) => RouteReturn<T>;
797
+ POST: (req: Request, config?: ExtensionConfig, ...args: unknown[]) => RouteReturn<T>;
798
+ DELETE: (req: Request, config?: ExtensionConfig, ...args: unknown[]) => RouteReturn<T>;
799
+ PUT: (req: Request, config?: ExtensionConfig, ...args: unknown[]) => RouteReturn<T>;
800
+ };
801
+ type ContextReturn<T = Response> = {
802
+ response: T;
803
+ nile: Server;
804
+ };
805
+ type CTXHandlerType = {
806
+ GET: <T = Response>(req: Request) => Promise<ContextReturn<T>>;
807
+ POST: <T = Response>(req: Request) => Promise<ContextReturn<T>>;
808
+ DELETE: <T = Response>(req: Request) => Promise<ContextReturn<T>>;
809
+ PUT: <T = Response>(req: Request) => Promise<ContextReturn<T>>;
810
+ };
811
+
812
+ declare const TENANT_COOKIE = "nile.tenant-id";
813
+ declare const USER_COOKIE = "nile.user-id";
814
+ declare const HEADER_ORIGIN = "nile-origin";
815
+ declare const HEADER_SECURE_COOKIES = "nile-secure-cookies";
512
816
 
513
- export { type APIError, APIErrorErrorCodeEnum, type ActiveSession, type AfterCreate, type CreateBasicUserRequest, type CreateTenantUserRequest, type JWT, type LoggerType, type LoginUserResponse, type LoginUserResponseToken, LoginUserResponseTokenTypeEnum, create as Nile, type NileConfig, type NileDb, type NilePoolConfig, type NileRequest, type NileResponse, type Opts, type Providers, Server, type Tenant, type User, parseCSRF, parseCallback, parseToken };
817
+ export { type APIError, APIErrorErrorCodeEnum, type ActiveSession, type AfterCreate, type CTX, type CTXHandlerType, type Context, type ContextReturn, type CreateBasicUserRequest, type CreateTenantUserRequest, type Extension, type ExtensionResult, ExtensionState, HEADER_ORIGIN, HEADER_SECURE_COOKIES, type Invite, type JWT, type LoggerType, type LoginUserResponse, type LoginUserResponseToken, LoginUserResponseTokenTypeEnum, create as Nile, type NileConfig, type NileDb, type NileHandlers, type NilePoolConfig, type NileRequest, type NileResponse, type Opts, type PartialContext, type Providers, type RouteFunctions, type RouteReturn, Server, TENANT_COOKIE, type Tenant, USER_COOKIE, type User, parseCSRF, parseCallback, parseResetToken, parseTenantId, parseToken };