@azlib/identity 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +387 -0
- package/dist/errors-BGMwaW5s.d.mts +481 -0
- package/dist/errors-BGMwaW5s.d.mts.map +1 -0
- package/dist/errors-Bcjx9o6g.cjs +111 -0
- package/dist/errors-C2xZAatu.d.cts +481 -0
- package/dist/errors-C2xZAatu.d.cts.map +1 -0
- package/dist/errors-CEmnZxIn.mjs +66 -0
- package/dist/errors-CEmnZxIn.mjs.map +1 -0
- package/dist/express.cjs +405 -0
- package/dist/express.d.cts +87 -0
- package/dist/express.d.cts.map +1 -0
- package/dist/express.d.mts +87 -0
- package/dist/express.d.mts.map +1 -0
- package/dist/express.mjs +401 -0
- package/dist/express.mjs.map +1 -0
- package/dist/identity-4eP45YIP.cjs +461 -0
- package/dist/identity-Bz9RDOvT.mjs +410 -0
- package/dist/identity-Bz9RDOvT.mjs.map +1 -0
- package/dist/identity-router-DBL20UWT.d.mts +115 -0
- package/dist/identity-router-DBL20UWT.d.mts.map +1 -0
- package/dist/identity-router-Dib30Waj.d.cts +115 -0
- package/dist/identity-router-Dib30Waj.d.cts.map +1 -0
- package/dist/identity-service-B9zrvE9z.d.mts +128 -0
- package/dist/identity-service-B9zrvE9z.d.mts.map +1 -0
- package/dist/identity-service-CLzKx8Z7.d.cts +128 -0
- package/dist/identity-service-CLzKx8Z7.d.cts.map +1 -0
- package/dist/identity-store-BRRahxcS.d.cts +272 -0
- package/dist/identity-store-BRRahxcS.d.cts.map +1 -0
- package/dist/identity-store-BRRahxcS.d.mts +272 -0
- package/dist/identity-store-BRRahxcS.d.mts.map +1 -0
- package/dist/index-CpufYgyn.d.cts +30 -0
- package/dist/index-CpufYgyn.d.cts.map +1 -0
- package/dist/index-CpufYgyn.d.mts +30 -0
- package/dist/index-CpufYgyn.d.mts.map +1 -0
- package/dist/index.cjs +18 -0
- package/dist/index.d.cts +4 -0
- package/dist/index.d.mts +4 -0
- package/dist/index.mjs +3 -0
- package/dist/logger-Be1wDzBC.cjs +48 -0
- package/dist/logger-CcCHJVVe.mjs +33 -0
- package/dist/logger-CcCHJVVe.mjs.map +1 -0
- package/dist/nestjs.cjs +516 -0
- package/dist/nestjs.d.cts +102 -0
- package/dist/nestjs.d.cts.map +1 -0
- package/dist/nestjs.d.mts +102 -0
- package/dist/nestjs.d.mts.map +1 -0
- package/dist/nestjs.mjs +500 -0
- package/dist/nestjs.mjs.map +1 -0
- package/dist/node.cjs +946 -0
- package/dist/node.d.cts +260 -0
- package/dist/node.d.cts.map +1 -0
- package/dist/node.d.mts +260 -0
- package/dist/node.d.mts.map +1 -0
- package/dist/node.mjs +890 -0
- package/dist/node.mjs.map +1 -0
- package/dist/test-utils.cjs +169 -0
- package/dist/test-utils.d.cts +12 -0
- package/dist/test-utils.d.cts.map +1 -0
- package/dist/test-utils.d.mts +12 -0
- package/dist/test-utils.d.mts.map +1 -0
- package/dist/test-utils.mjs +170 -0
- package/dist/test-utils.mjs.map +1 -0
- package/package.json +92 -0
- package/schema/model.ts +100 -0
- package/schema/mysql.sql +102 -0
- package/schema/postgres.sql +92 -0
- package/schema/prisma.schema +122 -0
- package/schema/sqlite.sql +92 -0
|
@@ -0,0 +1,410 @@
|
|
|
1
|
+
import { i as IdentityConfigError } from "./errors-CEmnZxIn.mjs";
|
|
2
|
+
import { r as resolveLogger } from "./logger-CcCHJVVe.mjs";
|
|
3
|
+
//#region core/config.ts
|
|
4
|
+
const MIN_SECRET_LENGTH = 32;
|
|
5
|
+
const defaultGenerateId = () => globalThis.crypto.randomUUID();
|
|
6
|
+
const defaultNow = () => /* @__PURE__ */ new Date();
|
|
7
|
+
/**
|
|
8
|
+
* Validates and applies defaults to consumer-provided configuration.
|
|
9
|
+
* Throws {@link IdentityConfigError} when required values are missing or invalid.
|
|
10
|
+
*/
|
|
11
|
+
function resolveIdentityConfig(input) {
|
|
12
|
+
if (!input.accessTokenSecret || input.accessTokenSecret.length < MIN_SECRET_LENGTH) throw new IdentityConfigError(`accessTokenSecret must be at least ${MIN_SECRET_LENGTH} characters.`);
|
|
13
|
+
const accessTokenTtlSeconds = input.accessTokenTtlSeconds ?? 900;
|
|
14
|
+
const refreshTokenTtlSeconds = input.refreshTokenTtlSeconds ?? 3600 * 24 * 14;
|
|
15
|
+
const passwordScryptCost = input.passwordScryptCost ?? 16384;
|
|
16
|
+
if (accessTokenTtlSeconds <= 0) throw new IdentityConfigError("accessTokenTtlSeconds must be positive.");
|
|
17
|
+
if (refreshTokenTtlSeconds <= accessTokenTtlSeconds) throw new IdentityConfigError("refreshTokenTtlSeconds must be greater than accessTokenTtlSeconds.");
|
|
18
|
+
if ((passwordScryptCost & passwordScryptCost - 1) !== 0) throw new IdentityConfigError("passwordScryptCost must be a power of two.");
|
|
19
|
+
return {
|
|
20
|
+
accessTokenSecret: input.accessTokenSecret,
|
|
21
|
+
accessTokenTtlSeconds,
|
|
22
|
+
refreshTokenTtlSeconds,
|
|
23
|
+
issuer: input.issuer ?? "azlib-identity",
|
|
24
|
+
audience: input.audience,
|
|
25
|
+
passwordScryptCost,
|
|
26
|
+
lockout: {
|
|
27
|
+
maxFailedAttempts: input.lockout?.maxFailedAttempts ?? 10,
|
|
28
|
+
durationSeconds: input.lockout?.durationSeconds ?? 900
|
|
29
|
+
},
|
|
30
|
+
now: input.overrides?.now ?? defaultNow,
|
|
31
|
+
generateId: input.overrides?.generateId ?? defaultGenerateId,
|
|
32
|
+
onEvent: input.overrides?.onEvent,
|
|
33
|
+
notifications: input.notifications,
|
|
34
|
+
logger: resolveLogger(input.logger)
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
//#endregion
|
|
38
|
+
//#region core/authorization.ts
|
|
39
|
+
const hasPermission = (principal, permission) => principal.permissions.includes(permission);
|
|
40
|
+
/**
|
|
41
|
+
* Evaluates a requirement using deny-by-default semantics:
|
|
42
|
+
* 1. If a `permission` is required and the principal lacks it, deny.
|
|
43
|
+
* 2. If a `policy` is provided, it must return `true` to allow.
|
|
44
|
+
* 3. If neither is provided, deny (nothing explicitly granted access).
|
|
45
|
+
*/
|
|
46
|
+
async function evaluateAuthorization(requirement, context) {
|
|
47
|
+
const { permission, policy } = requirement;
|
|
48
|
+
if (permission !== void 0 && !hasPermission(context.principal, permission)) return {
|
|
49
|
+
allowed: false,
|
|
50
|
+
reason: "missing-permission"
|
|
51
|
+
};
|
|
52
|
+
if (policy) {
|
|
53
|
+
if (await policy(context) !== true) return {
|
|
54
|
+
allowed: false,
|
|
55
|
+
reason: "policy-denied"
|
|
56
|
+
};
|
|
57
|
+
return {
|
|
58
|
+
allowed: true,
|
|
59
|
+
reason: "policy-allowed"
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
if (permission !== void 0) return {
|
|
63
|
+
allowed: true,
|
|
64
|
+
reason: "permission-granted"
|
|
65
|
+
};
|
|
66
|
+
return {
|
|
67
|
+
allowed: false,
|
|
68
|
+
reason: "no-grant"
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/** Convenience boolean form of {@link evaluateAuthorization}. */
|
|
72
|
+
async function isAuthorized(requirement, context) {
|
|
73
|
+
return (await evaluateAuthorization(requirement, context)).allowed;
|
|
74
|
+
}
|
|
75
|
+
//#endregion
|
|
76
|
+
//#region core/session-state.ts
|
|
77
|
+
/**
|
|
78
|
+
* Builds the runtime principal for a user by reading their roles and permissions from
|
|
79
|
+
* the store. Returns the shape attached to authenticated requests.
|
|
80
|
+
*/
|
|
81
|
+
async function hydratePrincipal(store, user) {
|
|
82
|
+
const [roles, permissions] = await Promise.all([store.listRolesForUser(user.userId), store.listPermissionsForUser(user.userId)]);
|
|
83
|
+
return {
|
|
84
|
+
userId: user.userId,
|
|
85
|
+
email: user.email,
|
|
86
|
+
displayName: user.displayName,
|
|
87
|
+
status: user.status,
|
|
88
|
+
emailVerified: user.emailVerifiedAt !== null,
|
|
89
|
+
roles: roles.map((role) => role.name),
|
|
90
|
+
permissions: [...permissions]
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Issues a fresh token pair for a user and persists a new refresh session
|
|
95
|
+
* (storing only the hash of the refresh token).
|
|
96
|
+
*/
|
|
97
|
+
async function issueSession(deps, user) {
|
|
98
|
+
const { config, store, tokenService } = deps;
|
|
99
|
+
const now = config.now();
|
|
100
|
+
const principal = await hydratePrincipal(store, user);
|
|
101
|
+
const access = await tokenService.issueAccessToken(user.userId, user.authVersion);
|
|
102
|
+
const sessionId = config.generateId();
|
|
103
|
+
const refresh = tokenService.createRefreshToken(sessionId);
|
|
104
|
+
const refreshExpiresAt = new Date(now.getTime() + config.refreshTokenTtlSeconds * 1e3);
|
|
105
|
+
await store.createSession({
|
|
106
|
+
sessionId,
|
|
107
|
+
userId: user.userId,
|
|
108
|
+
refreshTokenHash: refresh.hash,
|
|
109
|
+
createdAt: now,
|
|
110
|
+
expiresAt: refreshExpiresAt
|
|
111
|
+
});
|
|
112
|
+
return {
|
|
113
|
+
user: principal,
|
|
114
|
+
tokens: {
|
|
115
|
+
accessToken: access.token,
|
|
116
|
+
refreshToken: refresh.token,
|
|
117
|
+
accessTokenExpiresAt: access.expiresAt,
|
|
118
|
+
refreshTokenExpiresAt: refreshExpiresAt
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
//#endregion
|
|
123
|
+
//#region core/oauth/oauth-service.ts
|
|
124
|
+
/** Thrown when an OAuth operation targets an unregistered provider name. */
|
|
125
|
+
var OAuthProviderNotFoundError = class extends Error {
|
|
126
|
+
constructor(providerName) {
|
|
127
|
+
super(`No OAuth provider registered with name "${providerName}".`);
|
|
128
|
+
this.name = "OAuthProviderNotFoundError";
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
/** Thrown when the callback state does not match the expected state (CSRF guard). */
|
|
132
|
+
var OAuthStateMismatchError = class extends Error {
|
|
133
|
+
constructor() {
|
|
134
|
+
super("OAuth state mismatch. The callback may have been replayed or tampered with.");
|
|
135
|
+
this.name = "OAuthStateMismatchError";
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
/**
|
|
139
|
+
* Creates the OAuth2 / OIDC service. Wire into the identity service by passing configured
|
|
140
|
+
* provider instances (e.g. `createGoogleOAuthProvider(...)`) to the `oauth.providers` list
|
|
141
|
+
* in {@link IdentityConfigInput}.
|
|
142
|
+
*/
|
|
143
|
+
function createOAuthService(deps) {
|
|
144
|
+
const { providers, config, store, sessionDeps, audit } = deps;
|
|
145
|
+
const providerMap = /* @__PURE__ */ new Map();
|
|
146
|
+
for (const p of providers) providerMap.set(p.name, p);
|
|
147
|
+
function getProvider(name) {
|
|
148
|
+
const p = providerMap.get(name);
|
|
149
|
+
if (!p) throw new OAuthProviderNotFoundError(name);
|
|
150
|
+
return p;
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
get providers() {
|
|
154
|
+
return [...providerMap.keys()];
|
|
155
|
+
},
|
|
156
|
+
buildAuthorizationUrl(providerName, redirectUri, scopes) {
|
|
157
|
+
const provider = getProvider(providerName);
|
|
158
|
+
const state = config.generateId();
|
|
159
|
+
return {
|
|
160
|
+
url: provider.buildAuthorizationUrl({
|
|
161
|
+
redirectUri,
|
|
162
|
+
state,
|
|
163
|
+
scopes
|
|
164
|
+
}),
|
|
165
|
+
state
|
|
166
|
+
};
|
|
167
|
+
},
|
|
168
|
+
async handleCallback(providerName, params) {
|
|
169
|
+
if (params.state !== params.expectedState) throw new OAuthStateMismatchError();
|
|
170
|
+
const provider = getProvider(providerName);
|
|
171
|
+
const tokens = await provider.exchangeCode({
|
|
172
|
+
code: params.code,
|
|
173
|
+
redirectUri: params.redirectUri
|
|
174
|
+
});
|
|
175
|
+
const userInfo = await provider.fetchUserInfo(tokens);
|
|
176
|
+
const now = config.now();
|
|
177
|
+
if (store.findUserByOAuthId) {
|
|
178
|
+
const linkedUser = await store.findUserByOAuthId(providerName, userInfo.providerUserId);
|
|
179
|
+
if (linkedUser) {
|
|
180
|
+
await audit.record("user.login.succeeded", linkedUser.userId, {
|
|
181
|
+
email: linkedUser.email,
|
|
182
|
+
provider: providerName
|
|
183
|
+
});
|
|
184
|
+
return issueSession(sessionDeps, linkedUser);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (userInfo.email) {
|
|
188
|
+
const existingUser = await store.findUserByEmail(userInfo.email);
|
|
189
|
+
if (existingUser) {
|
|
190
|
+
await linkOAuthAccount(store, existingUser.userId, providerName, userInfo, now);
|
|
191
|
+
await audit.record("user.oauth.linked", existingUser.userId, {
|
|
192
|
+
provider: providerName,
|
|
193
|
+
providerUserId: userInfo.providerUserId
|
|
194
|
+
});
|
|
195
|
+
await audit.record("user.login.succeeded", existingUser.userId, {
|
|
196
|
+
email: existingUser.email,
|
|
197
|
+
provider: providerName
|
|
198
|
+
});
|
|
199
|
+
return issueSession(sessionDeps, existingUser);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
const newUser = await store.createUser({
|
|
203
|
+
userId: config.generateId(),
|
|
204
|
+
email: userInfo.email ?? `oauth:${providerName}:${userInfo.providerUserId}`,
|
|
205
|
+
displayName: userInfo.displayName,
|
|
206
|
+
status: "active",
|
|
207
|
+
authVersion: 0,
|
|
208
|
+
createdAt: now,
|
|
209
|
+
updatedAt: now
|
|
210
|
+
});
|
|
211
|
+
await linkOAuthAccount(store, newUser.userId, providerName, userInfo, now);
|
|
212
|
+
await audit.record("user.registered", newUser.userId, {
|
|
213
|
+
provider: providerName,
|
|
214
|
+
providerUserId: userInfo.providerUserId
|
|
215
|
+
});
|
|
216
|
+
await audit.record("user.oauth.linked", newUser.userId, {
|
|
217
|
+
provider: providerName,
|
|
218
|
+
providerUserId: userInfo.providerUserId
|
|
219
|
+
});
|
|
220
|
+
await audit.record("user.login.succeeded", newUser.userId, {
|
|
221
|
+
email: newUser.email,
|
|
222
|
+
provider: providerName
|
|
223
|
+
});
|
|
224
|
+
return issueSession(sessionDeps, newUser);
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
async function linkOAuthAccount(store, userId, provider, userInfo, now) {
|
|
229
|
+
if (!store.createOAuthLink) return;
|
|
230
|
+
const link = {
|
|
231
|
+
userId,
|
|
232
|
+
provider,
|
|
233
|
+
providerUserId: userInfo.providerUserId,
|
|
234
|
+
email: userInfo.email,
|
|
235
|
+
displayName: userInfo.displayName,
|
|
236
|
+
linkedAt: now
|
|
237
|
+
};
|
|
238
|
+
await store.createOAuthLink(link);
|
|
239
|
+
}
|
|
240
|
+
//#endregion
|
|
241
|
+
//#region schema/model.ts
|
|
242
|
+
const identitySchemaModel = { tables: [
|
|
243
|
+
{
|
|
244
|
+
name: "identity_users",
|
|
245
|
+
description: "Core user accounts.",
|
|
246
|
+
columns: [
|
|
247
|
+
{
|
|
248
|
+
name: "user_id",
|
|
249
|
+
description: "Primary key.",
|
|
250
|
+
nullable: false
|
|
251
|
+
},
|
|
252
|
+
{
|
|
253
|
+
name: "email",
|
|
254
|
+
description: "Unique, case-insensitive login email.",
|
|
255
|
+
nullable: false
|
|
256
|
+
},
|
|
257
|
+
{
|
|
258
|
+
name: "display_name",
|
|
259
|
+
description: "Optional display name.",
|
|
260
|
+
nullable: true
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
name: "status",
|
|
264
|
+
description: "active | disabled | locked.",
|
|
265
|
+
nullable: false
|
|
266
|
+
},
|
|
267
|
+
{
|
|
268
|
+
name: "email_verified_at",
|
|
269
|
+
description: "When email was verified.",
|
|
270
|
+
nullable: true
|
|
271
|
+
},
|
|
272
|
+
{
|
|
273
|
+
name: "auth_version",
|
|
274
|
+
description: "Token invalidation counter.",
|
|
275
|
+
nullable: false
|
|
276
|
+
},
|
|
277
|
+
{
|
|
278
|
+
name: "created_at",
|
|
279
|
+
description: "Creation timestamp.",
|
|
280
|
+
nullable: false
|
|
281
|
+
},
|
|
282
|
+
{
|
|
283
|
+
name: "updated_at",
|
|
284
|
+
description: "Last update timestamp.",
|
|
285
|
+
nullable: false
|
|
286
|
+
}
|
|
287
|
+
]
|
|
288
|
+
},
|
|
289
|
+
{
|
|
290
|
+
name: "identity_credentials",
|
|
291
|
+
description: "Password hashes, one per user.",
|
|
292
|
+
columns: [
|
|
293
|
+
{
|
|
294
|
+
name: "user_id",
|
|
295
|
+
description: "FK to identity_users.",
|
|
296
|
+
nullable: false
|
|
297
|
+
},
|
|
298
|
+
{
|
|
299
|
+
name: "password_hash",
|
|
300
|
+
description: "Algorithm-tagged hash.",
|
|
301
|
+
nullable: false
|
|
302
|
+
},
|
|
303
|
+
{
|
|
304
|
+
name: "updated_at",
|
|
305
|
+
description: "Last update timestamp.",
|
|
306
|
+
nullable: false
|
|
307
|
+
}
|
|
308
|
+
]
|
|
309
|
+
},
|
|
310
|
+
{
|
|
311
|
+
name: "identity_sessions",
|
|
312
|
+
description: "Server-side refresh sessions with hashed tokens.",
|
|
313
|
+
columns: [
|
|
314
|
+
{
|
|
315
|
+
name: "session_id",
|
|
316
|
+
description: "Primary key.",
|
|
317
|
+
nullable: false
|
|
318
|
+
},
|
|
319
|
+
{
|
|
320
|
+
name: "user_id",
|
|
321
|
+
description: "FK to identity_users.",
|
|
322
|
+
nullable: false
|
|
323
|
+
},
|
|
324
|
+
{
|
|
325
|
+
name: "refresh_token_hash",
|
|
326
|
+
description: "Hash of the active refresh token.",
|
|
327
|
+
nullable: false
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
name: "created_at",
|
|
331
|
+
description: "Creation timestamp.",
|
|
332
|
+
nullable: false
|
|
333
|
+
},
|
|
334
|
+
{
|
|
335
|
+
name: "expires_at",
|
|
336
|
+
description: "Expiry timestamp.",
|
|
337
|
+
nullable: false
|
|
338
|
+
},
|
|
339
|
+
{
|
|
340
|
+
name: "revoked_at",
|
|
341
|
+
description: "Set when rotated or revoked.",
|
|
342
|
+
nullable: true
|
|
343
|
+
}
|
|
344
|
+
]
|
|
345
|
+
},
|
|
346
|
+
{
|
|
347
|
+
name: "identity_roles",
|
|
348
|
+
description: "Named roles.",
|
|
349
|
+
columns: [
|
|
350
|
+
{
|
|
351
|
+
name: "role_id",
|
|
352
|
+
description: "Primary key.",
|
|
353
|
+
nullable: false
|
|
354
|
+
},
|
|
355
|
+
{
|
|
356
|
+
name: "name",
|
|
357
|
+
description: "Unique role name.",
|
|
358
|
+
nullable: false
|
|
359
|
+
},
|
|
360
|
+
{
|
|
361
|
+
name: "description",
|
|
362
|
+
description: "Optional description.",
|
|
363
|
+
nullable: true
|
|
364
|
+
}
|
|
365
|
+
]
|
|
366
|
+
},
|
|
367
|
+
{
|
|
368
|
+
name: "identity_user_roles",
|
|
369
|
+
description: "User-to-role assignments.",
|
|
370
|
+
columns: [{
|
|
371
|
+
name: "user_id",
|
|
372
|
+
description: "FK to identity_users.",
|
|
373
|
+
nullable: false
|
|
374
|
+
}, {
|
|
375
|
+
name: "role_id",
|
|
376
|
+
description: "FK to identity_roles.",
|
|
377
|
+
nullable: false
|
|
378
|
+
}]
|
|
379
|
+
},
|
|
380
|
+
{
|
|
381
|
+
name: "identity_role_permissions",
|
|
382
|
+
description: "Permissions granted to roles.",
|
|
383
|
+
columns: [{
|
|
384
|
+
name: "role_id",
|
|
385
|
+
description: "FK to identity_roles.",
|
|
386
|
+
nullable: false
|
|
387
|
+
}, {
|
|
388
|
+
name: "permission",
|
|
389
|
+
description: "Permission string.",
|
|
390
|
+
nullable: false
|
|
391
|
+
}]
|
|
392
|
+
},
|
|
393
|
+
{
|
|
394
|
+
name: "identity_user_permissions",
|
|
395
|
+
description: "Permissions granted directly to users.",
|
|
396
|
+
columns: [{
|
|
397
|
+
name: "user_id",
|
|
398
|
+
description: "FK to identity_users.",
|
|
399
|
+
nullable: false
|
|
400
|
+
}, {
|
|
401
|
+
name: "permission",
|
|
402
|
+
description: "Permission string.",
|
|
403
|
+
nullable: false
|
|
404
|
+
}]
|
|
405
|
+
}
|
|
406
|
+
] };
|
|
407
|
+
//#endregion
|
|
408
|
+
export { hydratePrincipal as a, isAuthorized as c, createOAuthService as i, resolveIdentityConfig as l, OAuthProviderNotFoundError as n, issueSession as o, OAuthStateMismatchError as r, evaluateAuthorization as s, identitySchemaModel as t };
|
|
409
|
+
|
|
410
|
+
//# sourceMappingURL=identity-Bz9RDOvT.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity-Bz9RDOvT.mjs","names":[],"sources":["../core/config.ts","../core/authorization.ts","../core/session-state.ts","../core/oauth/oauth-service.ts","../schema/model.ts"],"sourcesContent":["import { IdentityConfigError } from \"./errors\";\nimport type { IdentityLogger } from \"./logger\";\nimport { resolveLogger } from \"./logger\";\nimport type { NotificationService } from \"./notification\";\nimport type { IdentityEvent } from \"./types\";\n\n/**\n * Pluggable override points for advanced consumers. All are optional; sensible Node\n * defaults are supplied by the runtime entry (`@azlib/identity/node`).\n */\nexport interface IdentityOverrides {\n /** Returns the current time. Override in tests for deterministic clocks. */\n now?: () => Date;\n /** Generates a unique id (user ids, session ids). Defaults to `crypto.randomUUID`. */\n generateId?: () => string;\n /**\n * Lifecycle hook invoked for every audit event (registration, login, refresh, etc.).\n * Use it to forward events to your own logging/analytics pipeline. It must never throw\n * for normal operation; failures are swallowed so auditing cannot break auth flows.\n */\n onEvent?: (event: IdentityEvent) => void | Promise<void>;\n}\n\n/** Account lockout policy applied after repeated failed logins. */\nexport interface LockoutConfig {\n /**\n * How many consecutive failed login attempts are allowed before the account is\n * temporarily locked. Set to 0 to disable lockout. Default 10.\n */\n maxFailedAttempts: number;\n /**\n * How long (in seconds) a locked account is blocked before automatic unlock.\n * Default 900 (15 minutes). Set to 0 for permanent lock (manual unlock required).\n */\n durationSeconds: number;\n}\n\n/** Raw configuration accepted from consumers. */\nexport interface IdentityConfigInput {\n /**\n * Secret used to sign and verify access tokens (HMAC). Must be at least 32 characters.\n * Provide via environment, never hardcode.\n */\n accessTokenSecret: string;\n /** Access-token lifetime in seconds. Default 900 (15 minutes). */\n accessTokenTtlSeconds?: number;\n /** Refresh-token lifetime in seconds. Default 1209600 (14 days). */\n refreshTokenTtlSeconds?: number;\n /** Token issuer (`iss`). Default `azlib-identity`. */\n issuer?: string;\n /** Token audience (`aud`). Optional. */\n audience?: string;\n /** scrypt cost parameter `N`. Default 16384. */\n passwordScryptCost?: number;\n /**\n * Account lockout policy. Omit or set `maxFailedAttempts: 0` to disable. Default: 10\n * attempts, 15-minute lockout.\n */\n lockout?: Partial<LockoutConfig>;\n /**\n * Pluggable notification service for email verification, password reset, and SMS 2FA.\n * Omit if you do not need these features.\n */\n notifications?: NotificationService;\n /**\n * Logger used throughout the package. Pass your own `IdentityLogger` to route\n * diagnostic output to Winston, Pino, or any other provider. Pass `false` to silence\n * all logging. Defaults to a console-based logger when omitted.\n */\n logger?: IdentityLogger | false;\n /** Override points for clock and id generation. */\n overrides?: IdentityOverrides;\n}\n\n/** Fully resolved, validated configuration used internally. */\nexport interface IdentityConfig {\n accessTokenSecret: string;\n accessTokenTtlSeconds: number;\n refreshTokenTtlSeconds: number;\n issuer: string;\n audience: string | undefined;\n passwordScryptCost: number;\n lockout: LockoutConfig;\n notifications: NotificationService | undefined;\n /** Resolved logger; never `false` — `false` becomes {@link noopLogger}. */\n logger: IdentityLogger;\n now: () => Date;\n generateId: () => string;\n onEvent: ((event: IdentityEvent) => void | Promise<void>) | undefined;\n}\n\nconst MIN_SECRET_LENGTH = 32;\n\nconst defaultGenerateId = (): string => globalThis.crypto.randomUUID();\nconst defaultNow = (): Date => new Date();\n\n/**\n * Validates and applies defaults to consumer-provided configuration.\n * Throws {@link IdentityConfigError} when required values are missing or invalid.\n */\nexport function resolveIdentityConfig(input: IdentityConfigInput): IdentityConfig {\n if (!input.accessTokenSecret || input.accessTokenSecret.length < MIN_SECRET_LENGTH) {\n throw new IdentityConfigError(\n `accessTokenSecret must be at least ${MIN_SECRET_LENGTH} characters.`,\n );\n }\n\n const accessTokenTtlSeconds = input.accessTokenTtlSeconds ?? 900;\n const refreshTokenTtlSeconds = input.refreshTokenTtlSeconds ?? 60 * 60 * 24 * 14;\n const passwordScryptCost = input.passwordScryptCost ?? 16384;\n\n if (accessTokenTtlSeconds <= 0) {\n throw new IdentityConfigError(\"accessTokenTtlSeconds must be positive.\");\n }\n if (refreshTokenTtlSeconds <= accessTokenTtlSeconds) {\n throw new IdentityConfigError(\n \"refreshTokenTtlSeconds must be greater than accessTokenTtlSeconds.\",\n );\n }\n if ((passwordScryptCost & (passwordScryptCost - 1)) !== 0) {\n throw new IdentityConfigError(\"passwordScryptCost must be a power of two.\");\n }\n\n return {\n accessTokenSecret: input.accessTokenSecret,\n accessTokenTtlSeconds,\n refreshTokenTtlSeconds,\n issuer: input.issuer ?? \"azlib-identity\",\n audience: input.audience,\n passwordScryptCost,\n lockout: {\n maxFailedAttempts: input.lockout?.maxFailedAttempts ?? 10,\n durationSeconds: input.lockout?.durationSeconds ?? 900,\n },\n now: input.overrides?.now ?? defaultNow,\n generateId: input.overrides?.generateId ?? defaultGenerateId,\n onEvent: input.overrides?.onEvent,\n notifications: input.notifications,\n logger: resolveLogger(input.logger),\n };\n}\n","import type { AuthenticatedIdentity, Permission } from \"./types\";\n\n/**\n * Context passed to authorization checks. `resource` is an opaque consumer-supplied\n * object (e.g. a loaded document) used by ownership/relationship policies.\n */\nexport interface AuthorizationContext<TResource = unknown> {\n principal: AuthenticatedIdentity;\n /** The action being attempted, typically a permission string. */\n action: string;\n /** The target resource, if any. */\n resource?: TResource;\n}\n\n/**\n * A policy rule returns:\n * - `true` to allow,\n * - `false`/`undefined` to abstain (deny-by-default unless another rule allows),\n * It must never throw for normal \"denied\" outcomes.\n */\nexport type PolicyRule<TResource = unknown> = (\n context: AuthorizationContext<TResource>,\n) => boolean | undefined | Promise<boolean | undefined>;\n\n/** A named requirement combining a required permission and optional ownership policy. */\nexport interface AuthorizationRequirement<TResource = unknown> {\n /** Permission the principal must hold. Omit to rely solely on policies. */\n permission?: Permission;\n /** Optional ownership/relationship rule evaluated against the resource. */\n policy?: PolicyRule<TResource>;\n}\n\n/** Result of an authorization decision. */\nexport interface AuthorizationDecision {\n allowed: boolean;\n /** Non-sensitive reason for diagnostics/audit. */\n reason: string;\n}\n\nconst hasPermission = (\n principal: AuthenticatedIdentity,\n permission: Permission,\n): boolean => principal.permissions.includes(permission);\n\n/**\n * Evaluates a requirement using deny-by-default semantics:\n * 1. If a `permission` is required and the principal lacks it, deny.\n * 2. If a `policy` is provided, it must return `true` to allow.\n * 3. If neither is provided, deny (nothing explicitly granted access).\n */\nexport async function evaluateAuthorization<TResource = unknown>(\n requirement: AuthorizationRequirement<TResource>,\n context: AuthorizationContext<TResource>,\n): Promise<AuthorizationDecision> {\n const { permission, policy } = requirement;\n\n if (permission !== undefined && !hasPermission(context.principal, permission)) {\n return { allowed: false, reason: \"missing-permission\" };\n }\n\n if (policy) {\n const result = await policy(context);\n if (result !== true) {\n return { allowed: false, reason: \"policy-denied\" };\n }\n return { allowed: true, reason: \"policy-allowed\" };\n }\n\n if (permission !== undefined) {\n return { allowed: true, reason: \"permission-granted\" };\n }\n\n return { allowed: false, reason: \"no-grant\" };\n}\n\n/** Convenience boolean form of {@link evaluateAuthorization}. */\nexport async function isAuthorized<TResource = unknown>(\n requirement: AuthorizationRequirement<TResource>,\n context: AuthorizationContext<TResource>,\n): Promise<boolean> {\n return (await evaluateAuthorization(requirement, context)).allowed;\n}\n","import type { IdentityConfig } from \"./config\";\nimport type { IdentityStore } from \"./identity-store\";\nimport type { TokenService } from \"./token-service\";\nimport type { AuthResult, AuthenticatedIdentity, IdentityUser } from \"./types\";\n\n/** Dependencies shared by the register/login/refresh flows. */\nexport interface SessionDeps {\n config: IdentityConfig;\n store: IdentityStore;\n tokenService: TokenService;\n}\n\n/**\n * Builds the runtime principal for a user by reading their roles and permissions from\n * the store. Returns the shape attached to authenticated requests.\n */\nexport async function hydratePrincipal(\n store: IdentityStore,\n user: IdentityUser,\n): Promise<AuthenticatedIdentity> {\n const [roles, permissions] = await Promise.all([\n store.listRolesForUser(user.userId),\n store.listPermissionsForUser(user.userId),\n ]);\n\n return {\n userId: user.userId,\n email: user.email,\n displayName: user.displayName,\n status: user.status,\n emailVerified: user.emailVerifiedAt !== null,\n roles: roles.map((role) => role.name),\n permissions: [...permissions],\n };\n}\n\n/**\n * Issues a fresh token pair for a user and persists a new refresh session\n * (storing only the hash of the refresh token).\n */\nexport async function issueSession(\n deps: SessionDeps,\n user: IdentityUser,\n): Promise<AuthResult> {\n const { config, store, tokenService } = deps;\n const now = config.now();\n\n const principal = await hydratePrincipal(store, user);\n const access = await tokenService.issueAccessToken(user.userId, user.authVersion);\n const sessionId = config.generateId();\n const refresh = tokenService.createRefreshToken(sessionId);\n\n const refreshExpiresAt = new Date(now.getTime() + config.refreshTokenTtlSeconds * 1000);\n await store.createSession({\n sessionId,\n userId: user.userId,\n refreshTokenHash: refresh.hash,\n createdAt: now,\n expiresAt: refreshExpiresAt,\n });\n\n return {\n user: principal,\n tokens: {\n accessToken: access.token,\n refreshToken: refresh.token,\n accessTokenExpiresAt: access.expiresAt,\n refreshTokenExpiresAt: refreshExpiresAt,\n },\n };\n}\n","import type { AuditLogger } from \"../audit\";\nimport type { IdentityConfig } from \"../config\";\nimport type { IdentityStore } from \"../identity-store\";\nimport { issueSession, type SessionDeps } from \"../session-state\";\nimport type { AuthResult, OAuthLinkedAccount } from \"../types\";\nimport type { OAuthProvider } from \"./oauth-provider\";\n\n/** Result of {@link OAuthService.buildAuthorizationUrl}. */\nexport interface OAuthAuthorizationUrl {\n /** The full provider authorization URL to redirect the user to. */\n url: string;\n /**\n * An opaque CSRF-prevention state value. Store this in a signed cookie or server\n * session and pass it as `expectedState` when calling {@link OAuthService.handleCallback}.\n */\n state: string;\n}\n\n/** Parameters for {@link OAuthService.handleCallback}. */\nexport interface OAuthCallbackParams {\n /** The authorization code received from the provider callback query string. */\n code: string;\n /** The `state` value received from the provider callback query string. */\n state: string;\n /**\n * The expected state value previously returned by {@link OAuthService.buildAuthorizationUrl}.\n * The callback will be rejected when they do not match (CSRF protection).\n */\n expectedState: string;\n /** The same redirect URI that was used in the authorization request. */\n redirectUri: string;\n /** Optional scopes to override for this callback's code exchange. */\n scopes?: string[];\n}\n\n/** The OAuth2 / OIDC surface of the identity service. */\nexport interface OAuthService {\n /** Returns the registered provider names, e.g. `[\"google\", \"microsoft\"]`. */\n readonly providers: readonly string[];\n\n /**\n * Builds the authorization URL for the given provider. Redirect the user's browser to\n * the returned `url`, then store `state` for later verification.\n */\n buildAuthorizationUrl(providerName: string, redirectUri: string, scopes?: string[]): OAuthAuthorizationUrl;\n\n /**\n * Handles the provider callback after user consent. Verifies state, exchanges the code\n * for tokens, resolves or provisions a local user, and returns a full auth result.\n *\n * Throws {@link OAuthProviderNotFoundError} for unknown providers.\n * Throws a generic {@link IdentityError} when state mismatches (CSRF guard).\n */\n handleCallback(providerName: string, params: OAuthCallbackParams): Promise<AuthResult>;\n}\n\n/** Thrown when an OAuth operation targets an unregistered provider name. */\nexport class OAuthProviderNotFoundError extends Error {\n constructor(providerName: string) {\n super(`No OAuth provider registered with name \"${providerName}\".`);\n this.name = \"OAuthProviderNotFoundError\";\n }\n}\n\n/** Thrown when the callback state does not match the expected state (CSRF guard). */\nexport class OAuthStateMismatchError extends Error {\n constructor() {\n super(\"OAuth state mismatch. The callback may have been replayed or tampered with.\");\n this.name = \"OAuthStateMismatchError\";\n }\n}\n\n/** Dependencies for {@link createOAuthService}. */\nexport interface OAuthServiceDeps {\n providers: readonly OAuthProvider[];\n config: IdentityConfig;\n store: IdentityStore;\n sessionDeps: SessionDeps;\n audit: AuditLogger;\n}\n\n/**\n * Creates the OAuth2 / OIDC service. Wire into the identity service by passing configured\n * provider instances (e.g. `createGoogleOAuthProvider(...)`) to the `oauth.providers` list\n * in {@link IdentityConfigInput}.\n */\nexport function createOAuthService(deps: OAuthServiceDeps): OAuthService {\n const { providers, config, store, sessionDeps, audit } = deps;\n\n const providerMap = new Map<string, OAuthProvider>();\n for (const p of providers) {\n providerMap.set(p.name, p);\n }\n\n function getProvider(name: string): OAuthProvider {\n const p = providerMap.get(name);\n if (!p) throw new OAuthProviderNotFoundError(name);\n return p;\n }\n\n return {\n get providers() {\n return [...providerMap.keys()];\n },\n\n buildAuthorizationUrl(providerName, redirectUri, scopes) {\n const provider = getProvider(providerName);\n const state = config.generateId();\n const url = provider.buildAuthorizationUrl({ redirectUri, state, scopes });\n return { url, state };\n },\n\n async handleCallback(providerName, params) {\n // CSRF guard — must be the first check.\n if (params.state !== params.expectedState) {\n throw new OAuthStateMismatchError();\n }\n\n const provider = getProvider(providerName);\n\n // Exchange the authorization code for provider tokens.\n const tokens = await provider.exchangeCode({\n code: params.code,\n redirectUri: params.redirectUri,\n });\n\n // Fetch normalized user info from the provider.\n const userInfo = await provider.fetchUserInfo(tokens);\n\n const now = config.now();\n\n // 1. Look up by OAuth link (returning user).\n if (store.findUserByOAuthId) {\n const linkedUser = await store.findUserByOAuthId(providerName, userInfo.providerUserId);\n if (linkedUser) {\n await audit.record(\"user.login.succeeded\", linkedUser.userId, {\n email: linkedUser.email,\n provider: providerName,\n });\n return issueSession(sessionDeps, linkedUser);\n }\n }\n\n // 2. Look up by email (existing local account — link the provider).\n if (userInfo.email) {\n const existingUser = await store.findUserByEmail(userInfo.email);\n if (existingUser) {\n await linkOAuthAccount(store, existingUser.userId, providerName, userInfo, now);\n await audit.record(\"user.oauth.linked\", existingUser.userId, {\n provider: providerName,\n providerUserId: userInfo.providerUserId,\n });\n await audit.record(\"user.login.succeeded\", existingUser.userId, {\n email: existingUser.email,\n provider: providerName,\n });\n return issueSession(sessionDeps, existingUser);\n }\n }\n\n // 3. Provision a new local user and link the provider.\n const newUser = await store.createUser({\n userId: config.generateId(),\n email: userInfo.email ?? `oauth:${providerName}:${userInfo.providerUserId}`,\n displayName: userInfo.displayName,\n status: \"active\",\n authVersion: 0,\n createdAt: now,\n updatedAt: now,\n });\n await linkOAuthAccount(store, newUser.userId, providerName, userInfo, now);\n await audit.record(\"user.registered\", newUser.userId, {\n provider: providerName,\n providerUserId: userInfo.providerUserId,\n });\n await audit.record(\"user.oauth.linked\", newUser.userId, {\n provider: providerName,\n providerUserId: userInfo.providerUserId,\n });\n await audit.record(\"user.login.succeeded\", newUser.userId, {\n email: newUser.email,\n provider: providerName,\n });\n return issueSession(sessionDeps, newUser);\n },\n };\n}\n\nasync function linkOAuthAccount(\n store: IdentityStore,\n userId: string,\n provider: string,\n userInfo: { providerUserId: string; email: string | null; displayName: string | null },\n now: Date,\n): Promise<void> {\n if (!store.createOAuthLink) return; // Store does not support OAuth links — skip silently.\n\n const link: OAuthLinkedAccount = {\n userId,\n provider,\n providerUserId: userInfo.providerUserId,\n email: userInfo.email,\n displayName: userInfo.displayName,\n linkedAt: now,\n };\n await store.createOAuthLink(link);\n}\n","/**\n * Logical description of the relational schema `@azlib/identity` expects.\n *\n * Concrete DDL is shipped alongside this module:\n * - `@azlib/identity/schema/postgres.sql`\n * - `@azlib/identity/schema/mysql.sql`\n * - `@azlib/identity/schema/sqlite.sql`\n * - `@azlib/identity/schema/prisma.schema`\n *\n * This object is documentation-as-data so consumers and tooling can introspect the\n * expected tables without parsing SQL.\n */\nexport interface SchemaColumn {\n name: string;\n description: string;\n nullable: boolean;\n}\n\nexport interface SchemaTable {\n name: string;\n description: string;\n columns: readonly SchemaColumn[];\n}\n\nexport interface SchemaModel {\n tables: readonly SchemaTable[];\n}\n\nexport const identitySchemaModel: SchemaModel = {\n tables: [\n {\n name: \"identity_users\",\n description: \"Core user accounts.\",\n columns: [\n { name: \"user_id\", description: \"Primary key.\", nullable: false },\n { name: \"email\", description: \"Unique, case-insensitive login email.\", nullable: false },\n { name: \"display_name\", description: \"Optional display name.\", nullable: true },\n { name: \"status\", description: \"active | disabled | locked.\", nullable: false },\n { name: \"email_verified_at\", description: \"When email was verified.\", nullable: true },\n { name: \"auth_version\", description: \"Token invalidation counter.\", nullable: false },\n { name: \"created_at\", description: \"Creation timestamp.\", nullable: false },\n { name: \"updated_at\", description: \"Last update timestamp.\", nullable: false },\n ],\n },\n {\n name: \"identity_credentials\",\n description: \"Password hashes, one per user.\",\n columns: [\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: false },\n { name: \"password_hash\", description: \"Algorithm-tagged hash.\", nullable: false },\n { name: \"updated_at\", description: \"Last update timestamp.\", nullable: false },\n ],\n },\n {\n name: \"identity_sessions\",\n description: \"Server-side refresh sessions with hashed tokens.\",\n columns: [\n { name: \"session_id\", description: \"Primary key.\", nullable: false },\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: false },\n { name: \"refresh_token_hash\", description: \"Hash of the active refresh token.\", nullable: false },\n { name: \"created_at\", description: \"Creation timestamp.\", nullable: false },\n { name: \"expires_at\", description: \"Expiry timestamp.\", nullable: false },\n { name: \"revoked_at\", description: \"Set when rotated or revoked.\", nullable: true },\n ],\n },\n {\n name: \"identity_roles\",\n description: \"Named roles.\",\n columns: [\n { name: \"role_id\", description: \"Primary key.\", nullable: false },\n { name: \"name\", description: \"Unique role name.\", nullable: false },\n { name: \"description\", description: \"Optional description.\", nullable: true },\n ],\n },\n {\n name: \"identity_user_roles\",\n description: \"User-to-role assignments.\",\n columns: [\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: false },\n { name: \"role_id\", description: \"FK to identity_roles.\", nullable: false },\n ],\n },\n {\n name: \"identity_role_permissions\",\n description: \"Permissions granted to roles.\",\n columns: [\n { name: \"role_id\", description: \"FK to identity_roles.\", nullable: false },\n { name: \"permission\", description: \"Permission string.\", nullable: false },\n ],\n },\n {\n name: \"identity_user_permissions\",\n description: \"Permissions granted directly to users.\",\n columns: [\n { name: \"user_id\", description: \"FK to identity_users.\", nullable: false },\n { name: \"permission\", description: \"Permission string.\", nullable: false },\n ],\n },\n ],\n};\n"],"mappings":";;;AA2FA,MAAM,oBAAoB;AAE1B,MAAM,0BAAkC,WAAW,OAAO,WAAW;AACrE,MAAM,mCAAyB,IAAI,KAAK;;;;;AAMxC,SAAgB,sBAAsB,OAA4C;CAChF,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GAAE,MAAM;GAAc,aAAa;GAAsB,UAAU;EAAM,CAC3E;CACF;CACA;EACE,MAAM;EACN,aAAa;EACb,SAAS,CACP;GAAE,MAAM;GAAW,aAAa;GAAyB,UAAU;EAAM,GACzE;GAAE,MAAM;GAAc,aAAa;GAAsB,UAAU;EAAM,CAC3E;CACF;AACF,EACF"}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { F as IdentityLogger } from "./errors-BGMwaW5s.mjs";
|
|
2
|
+
import { t as IdentityService } from "./identity-service-B9zrvE9z.mjs";
|
|
3
|
+
import { Request, Response, Router } from "express";
|
|
4
|
+
|
|
5
|
+
//#region core/express/identity-router.d.ts
|
|
6
|
+
/** Options for controlling the refresh-token cookie. */
|
|
7
|
+
interface CookieRefreshOptions {
|
|
8
|
+
/** Cookie name. Default: `"azlib_rt"`. */
|
|
9
|
+
name?: string;
|
|
10
|
+
/** Mark the cookie as `HttpOnly`. Default: `true`. */
|
|
11
|
+
httpOnly?: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Mark the cookie as `Secure`. Defaults to `true` when `NODE_ENV` is `"production"`,
|
|
14
|
+
* `false` otherwise.
|
|
15
|
+
*/
|
|
16
|
+
secure?: boolean;
|
|
17
|
+
/** `SameSite` policy. Default: `"lax"`. */
|
|
18
|
+
sameSite?: "strict" | "lax" | "none";
|
|
19
|
+
/** Cookie path. Default: `"/"`. */
|
|
20
|
+
path?: string;
|
|
21
|
+
/** Cookie domain. Omit to use the current host. */
|
|
22
|
+
domain?: string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Options for {@link createIdentityRouter}.
|
|
26
|
+
*/
|
|
27
|
+
interface IdentityRouterOptions {
|
|
28
|
+
/**
|
|
29
|
+
* Controls how the refresh token is transported between server and client.
|
|
30
|
+
*
|
|
31
|
+
* - **`"body"`** (default) — the refresh token is included in the `tokens` object of
|
|
32
|
+
* every successful `register`/`login`/`refresh` response. The client must store it
|
|
33
|
+
* and send it back via the JSON body on `/refresh` and `/logout`.
|
|
34
|
+
*
|
|
35
|
+
* - **`{ cookie: CookieRefreshOptions }`** — the refresh token is sent as an
|
|
36
|
+
* `HttpOnly` cookie. `/refresh` and `/logout` read it automatically; the response
|
|
37
|
+
* body only includes the access token.
|
|
38
|
+
*/
|
|
39
|
+
refreshToken?: "body" | {
|
|
40
|
+
cookie: CookieRefreshOptions;
|
|
41
|
+
};
|
|
42
|
+
/**
|
|
43
|
+
* Base URL under which the OAuth callback routes are hosted.
|
|
44
|
+
*
|
|
45
|
+
* Example: `"https://api.example.com/auth"`.
|
|
46
|
+
*
|
|
47
|
+
* The callback URI for a provider becomes `{oauthBaseUrl}/{providerName}/callback`.
|
|
48
|
+
* Required when the identity service has OAuth providers configured.
|
|
49
|
+
*/
|
|
50
|
+
oauthBaseUrl?: string;
|
|
51
|
+
/**
|
|
52
|
+
* URL path prefix prepended to all identity routes.
|
|
53
|
+
*
|
|
54
|
+
* Default: `"account"`. Routes are served at `/{prefix}/login`, `/{prefix}/register`, etc.
|
|
55
|
+
*
|
|
56
|
+
* Mount the returned router at the application root:
|
|
57
|
+
* ```ts
|
|
58
|
+
* app.use(createIdentityRouter(service, { prefix: "auth" }));
|
|
59
|
+
* // → POST /auth/login, POST /auth/register, …
|
|
60
|
+
* ```
|
|
61
|
+
*
|
|
62
|
+
* Set to `""` to omit the prefix and mount routes directly at the router's mount point.
|
|
63
|
+
*/
|
|
64
|
+
prefix?: string;
|
|
65
|
+
/**
|
|
66
|
+
* Logger for request/response and error diagnostics.
|
|
67
|
+
*
|
|
68
|
+
* - Omit — defaults to a `console`-based logger with an `[identity]` prefix.
|
|
69
|
+
* - Supply your own `IdentityLogger` — route output to Winston, Pino, etc.
|
|
70
|
+
* - Pass `false` — disable all logging from this router.
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```ts
|
|
74
|
+
* import pino from "pino";
|
|
75
|
+
* app.use(createIdentityRouter(service, { logger: pino() }));
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
logger?: IdentityLogger | false;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Creates a pre-wired Express `Router` with all standard identity endpoints.
|
|
82
|
+
*
|
|
83
|
+
* Mount it once on your application:
|
|
84
|
+
* ```ts
|
|
85
|
+
* import express from "express";
|
|
86
|
+
* import { createIdentityService } from "@azlib/identity/node";
|
|
87
|
+
* import { createIdentityRouter, identityErrorHandler } from "@azlib/identity/express";
|
|
88
|
+
*
|
|
89
|
+
* const service = createIdentityService(config, store);
|
|
90
|
+
* const app = express();
|
|
91
|
+
*
|
|
92
|
+
* app.use(express.json());
|
|
93
|
+
* // Routes are served at /account/login, /account/register, etc. (default prefix)
|
|
94
|
+
* app.use(createIdentityRouter(service));
|
|
95
|
+
* // Or use a custom prefix:
|
|
96
|
+
* app.use(createIdentityRouter(service, { prefix: "auth" }));
|
|
97
|
+
* app.use(identityErrorHandler()); // optional convenience error handler
|
|
98
|
+
* ```
|
|
99
|
+
*
|
|
100
|
+
* Pre-wired routes:
|
|
101
|
+
*
|
|
102
|
+
* | Method | Path | Description |
|
|
103
|
+
* |--------|------|-------------|
|
|
104
|
+
* | POST | `/register` | Create a new account |
|
|
105
|
+
* | POST | `/login` | Email + password login |
|
|
106
|
+
* | POST | `/refresh` | Rotate the refresh token |
|
|
107
|
+
* | POST | `/logout` | Revoke the current session |
|
|
108
|
+
* | GET | `/me` | Return the authenticated principal |
|
|
109
|
+
* | GET | `/:provider` | Start an OAuth 2.0 authorisation flow *(optional)* |
|
|
110
|
+
* | GET | `/:provider/callback` | Handle an OAuth 2.0 callback *(optional)* |
|
|
111
|
+
*/
|
|
112
|
+
declare function createIdentityRouter(service: IdentityService, options?: IdentityRouterOptions): Router;
|
|
113
|
+
//#endregion
|
|
114
|
+
export { IdentityRouterOptions as n, createIdentityRouter as r, CookieRefreshOptions as t };
|
|
115
|
+
//# sourceMappingURL=identity-router-DBL20UWT.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity-router-DBL20UWT.d.mts","names":[],"sources":["../core/express/identity-router.ts"],"mappings":";;;;;;UAeiB,oBAAA;EAAA;EAEf,IAAA;;EAEA,QAAA;EAFA;;;;EAOA,MAAA;EAMA;EAJA,QAAA;EAIM;EAFN,IAAA;EAQoC;EANpC,MAAA;AAAA;;;;UAMe,qBAAA;EAqCf;;;;AAeuB;AAsIzB;;;;;;EA9KE,YAAA;IAA0B,MAAA,EAAQ,oBAAA;EAAA;EA+KlC;;;;;AAEO;;;EAvKP,YAAA;;;;;;;;;;;;;;EAeA,MAAA;;;;;;;;;;;;;;EAeA,MAAA,GAAS,cAAc;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsIT,oBAAA,CACd,OAAA,EAAS,eAAA,EACT,OAAA,GAAS,qBAAA,GACR,MAAA"}
|