@niledatabase/server 5.0.0-alpha.2 → 5.0.0-alpha.21

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