@auth-craft/worker-d1-stack 0.0.0-stage → 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/CHANGELOG.md +75 -0
- package/README.md +296 -2
- package/assets/check/config.mjs +1935 -0
- package/assets/data/snapshot.mjs +190 -0
- package/assets/engine/dev-engine.mjs +1 -0
- package/assets/manifest.json +113 -0
- package/assets/migrations/0001_baseline.sql +234 -0
- package/assets/migrations/0002_email.sql +31 -0
- package/assets/migrations/0003_email_provider_index.sql +7 -0
- package/assets/migrations/0004_audit.sql +27 -0
- package/assets/migrations/0005_allowed_origins.sql +14 -0
- package/assets/sbom/data.cdx.json +1042 -0
- package/assets/sbom/worker.cdx.json +647 -0
- package/assets/worker/worker.js +158 -0
- package/bin/auth-craft-worker.mjs +4 -0
- package/dist/check.d.ts +9 -0
- package/dist/check.d.ts.map +1 -0
- package/dist/check.js +125 -0
- package/dist/check.js.map +1 -0
- package/dist/cli.d.ts +14 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +433 -0
- package/dist/cli.js.map +1 -0
- package/dist/commands.d.ts +39 -0
- package/dist/commands.d.ts.map +1 -0
- package/dist/commands.js +108 -0
- package/dist/commands.js.map +1 -0
- package/dist/cutover.d.ts +63 -0
- package/dist/cutover.d.ts.map +1 -0
- package/dist/cutover.js +310 -0
- package/dist/cutover.js.map +1 -0
- package/dist/data.d.ts +52 -0
- package/dist/data.d.ts.map +1 -0
- package/dist/data.js +131 -0
- package/dist/data.js.map +1 -0
- package/dist/dev.d.ts +16 -0
- package/dist/dev.d.ts.map +1 -0
- package/dist/dev.js +80 -0
- package/dist/dev.js.map +1 -0
- package/dist/init.d.ts +23 -0
- package/dist/init.d.ts.map +1 -0
- package/dist/init.js +71 -0
- package/dist/init.js.map +1 -0
- package/dist/paths.d.ts +17 -0
- package/dist/paths.d.ts.map +1 -0
- package/dist/paths.js +13 -0
- package/dist/paths.js.map +1 -0
- package/dist/preflight.d.ts +45 -0
- package/dist/preflight.d.ts.map +1 -0
- package/dist/preflight.js +335 -0
- package/dist/preflight.js.map +1 -0
- package/dist/secrets-file.d.ts +5 -0
- package/dist/secrets-file.d.ts.map +1 -0
- package/dist/secrets-file.js +57 -0
- package/dist/secrets-file.js.map +1 -0
- package/dist/service-token.d.ts +6 -0
- package/dist/service-token.d.ts.map +1 -0
- package/dist/service-token.js +26 -0
- package/dist/service-token.js.map +1 -0
- package/dist/smoke.d.ts +45 -0
- package/dist/smoke.d.ts.map +1 -0
- package/dist/smoke.js +186 -0
- package/dist/smoke.js.map +1 -0
- package/dist/wrangler-config.d.ts +52 -0
- package/dist/wrangler-config.d.ts.map +1 -0
- package/dist/wrangler-config.js +23 -0
- package/dist/wrangler-config.js.map +1 -0
- package/dist/wrangler-runner.d.ts +13 -0
- package/dist/wrangler-runner.d.ts.map +1 -0
- package/dist/wrangler-runner.js +52 -0
- package/dist/wrangler-runner.js.map +1 -0
- package/package.json +42 -3
|
@@ -0,0 +1,1935 @@
|
|
|
1
|
+
// packages/auth-core/dist/core/apps.js
|
|
2
|
+
var DEFAULT_SYSTEM_TENANT_ID = "__system__";
|
|
3
|
+
var APP_ID_PATTERN = /^[a-z][a-z0-9-]{1,31}$/;
|
|
4
|
+
var RESERVED_APP_IDS = /* @__PURE__ */ new Set([
|
|
5
|
+
"auth",
|
|
6
|
+
"mfa",
|
|
7
|
+
"oauth",
|
|
8
|
+
"password",
|
|
9
|
+
"sessions",
|
|
10
|
+
"tenants",
|
|
11
|
+
"users",
|
|
12
|
+
"verification",
|
|
13
|
+
"internal",
|
|
14
|
+
"api",
|
|
15
|
+
"health",
|
|
16
|
+
"auth-health",
|
|
17
|
+
"well-known"
|
|
18
|
+
]);
|
|
19
|
+
function systemTenantOf(security) {
|
|
20
|
+
return security.systemTenantId ?? DEFAULT_SYSTEM_TENANT_ID;
|
|
21
|
+
}
|
|
22
|
+
function presets(security) {
|
|
23
|
+
const aud = security.tokenAudiences;
|
|
24
|
+
const cookies = aud?.cookieNames;
|
|
25
|
+
return {
|
|
26
|
+
customer: {
|
|
27
|
+
id: "customer",
|
|
28
|
+
audience: aud?.customer,
|
|
29
|
+
...cookies?.customer && { cookieName: cookies.customer },
|
|
30
|
+
tenancy: { mode: "none" },
|
|
31
|
+
access: { mode: "open" }
|
|
32
|
+
},
|
|
33
|
+
tenant: {
|
|
34
|
+
id: "tenant",
|
|
35
|
+
audience: aud?.tenant,
|
|
36
|
+
...cookies?.tenant && { cookieName: cookies.tenant },
|
|
37
|
+
tenancy: { mode: "selectable" },
|
|
38
|
+
access: { mode: "open" }
|
|
39
|
+
},
|
|
40
|
+
system: {
|
|
41
|
+
id: "system",
|
|
42
|
+
audience: aud?.system,
|
|
43
|
+
...cookies?.system && { cookieName: cookies.system },
|
|
44
|
+
tenancy: { mode: "fixed", tenantId: systemTenantOf(security) },
|
|
45
|
+
access: { mode: "members" }
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function resolveApps(security) {
|
|
50
|
+
if (!security.apps)
|
|
51
|
+
return new Map(Object.entries(presets(security)));
|
|
52
|
+
return new Map(Object.entries(security.apps).map(([id, def]) => [id, { ...def, id, audience: def.audience ?? id }]));
|
|
53
|
+
}
|
|
54
|
+
function defaultAppId(security) {
|
|
55
|
+
return security.defaultApp ?? "customer";
|
|
56
|
+
}
|
|
57
|
+
function validateApps(security, options = {}) {
|
|
58
|
+
const errors = [];
|
|
59
|
+
const apps = resolveApps(security);
|
|
60
|
+
const systemTenantId = systemTenantOf(security);
|
|
61
|
+
if (!apps.has(defaultAppId(security)))
|
|
62
|
+
errors.push(`defaultApp "${defaultAppId(security)}" is not a configured app`);
|
|
63
|
+
if (!security.apps)
|
|
64
|
+
return errors;
|
|
65
|
+
const audiences = /* @__PURE__ */ new Map();
|
|
66
|
+
const cookies = /* @__PURE__ */ new Map();
|
|
67
|
+
for (const app of apps.values()) {
|
|
68
|
+
if (!APP_ID_PATTERN.test(app.id))
|
|
69
|
+
errors.push(`app id "${app.id}" must match ${APP_ID_PATTERN}`);
|
|
70
|
+
if (RESERVED_APP_IDS.has(app.id))
|
|
71
|
+
errors.push(`app id "${app.id}" is reserved`);
|
|
72
|
+
if (app.audience !== void 0) {
|
|
73
|
+
const other = audiences.get(app.audience);
|
|
74
|
+
if (other)
|
|
75
|
+
errors.push(`apps "${other}" and "${app.id}" share audience "${app.audience}"`);
|
|
76
|
+
audiences.set(app.audience, app.id);
|
|
77
|
+
}
|
|
78
|
+
if (app.cookieName !== void 0) {
|
|
79
|
+
const other = cookies.get(app.cookieName);
|
|
80
|
+
if (other)
|
|
81
|
+
errors.push(`apps "${other}" and "${app.id}" share cookie "${app.cookieName}"`);
|
|
82
|
+
cookies.set(app.cookieName, app.id);
|
|
83
|
+
}
|
|
84
|
+
if (app.tenancy.mode === "selectable" && app.tenancy.tenantTypes?.includes("system")) {
|
|
85
|
+
errors.push(`app "${app.id}": the system tenant type is never selectable`);
|
|
86
|
+
}
|
|
87
|
+
if (app.access.mode === "hook" && options.hasAccessHook === false) {
|
|
88
|
+
errors.push(`app "${app.id}": access "hook" needs an appAccess plugin`);
|
|
89
|
+
}
|
|
90
|
+
if (app.access.mode === "members" && app.tenancy.mode !== "fixed") {
|
|
91
|
+
errors.push(`app "${app.id}": access "members" needs tenancy "fixed"`);
|
|
92
|
+
}
|
|
93
|
+
if (app.tenancy.mode === "fixed" && app.tenancy.tenantId === systemTenantId && app.access.mode !== "members") {
|
|
94
|
+
errors.push(`app "${app.id}": the system tenant needs access "members"`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return errors;
|
|
98
|
+
}
|
|
99
|
+
var APP_KEYS = /* @__PURE__ */ new Set(["audience", "cookieName", "tokenStrategy", "tenancy", "access"]);
|
|
100
|
+
var STRATEGIES = /* @__PURE__ */ new Set(["body", "cookie", "both"]);
|
|
101
|
+
function isRecord(value) {
|
|
102
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
103
|
+
}
|
|
104
|
+
function parseTenancy(id, value, errors) {
|
|
105
|
+
if (!isRecord(value))
|
|
106
|
+
return void errors.push(`app "${id}": tenancy must be an object`);
|
|
107
|
+
const extra = Object.keys(value).filter((k) => !["mode", "tenantId", "tenantTypes"].includes(k));
|
|
108
|
+
if (extra.length > 0)
|
|
109
|
+
errors.push(`app "${id}": unknown tenancy field(s) ${extra.join(", ")}`);
|
|
110
|
+
switch (value.mode) {
|
|
111
|
+
case "none":
|
|
112
|
+
return { mode: "none" };
|
|
113
|
+
case "fixed":
|
|
114
|
+
if (typeof value.tenantId !== "string" || value.tenantId === "") {
|
|
115
|
+
return void errors.push(`app "${id}": tenancy "fixed" needs a tenantId`);
|
|
116
|
+
}
|
|
117
|
+
return { mode: "fixed", tenantId: value.tenantId };
|
|
118
|
+
case "selectable": {
|
|
119
|
+
const types = value.tenantTypes;
|
|
120
|
+
if (types === void 0)
|
|
121
|
+
return { mode: "selectable" };
|
|
122
|
+
if (!Array.isArray(types) || types.some((t) => typeof t !== "string" || t === "")) {
|
|
123
|
+
return void errors.push(`app "${id}": tenantTypes must be a list of tenant types`);
|
|
124
|
+
}
|
|
125
|
+
return { mode: "selectable", tenantTypes: types };
|
|
126
|
+
}
|
|
127
|
+
default:
|
|
128
|
+
return void errors.push(`app "${id}": tenancy.mode must be none | fixed | selectable`);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function parseAccess(id, value, errors) {
|
|
132
|
+
if (!isRecord(value))
|
|
133
|
+
return void errors.push(`app "${id}": access must be an object`);
|
|
134
|
+
const extra = Object.keys(value).filter((k) => !["mode", "recheckOnRefresh"].includes(k));
|
|
135
|
+
if (extra.length > 0)
|
|
136
|
+
errors.push(`app "${id}": unknown access field(s) ${extra.join(", ")}`);
|
|
137
|
+
if (value.mode === "open" || value.mode === "members") {
|
|
138
|
+
if (value.recheckOnRefresh !== void 0)
|
|
139
|
+
errors.push(`app "${id}": recheckOnRefresh is for access "hook"`);
|
|
140
|
+
return { mode: value.mode };
|
|
141
|
+
}
|
|
142
|
+
if (value.mode === "hook") {
|
|
143
|
+
if (value.recheckOnRefresh !== void 0 && typeof value.recheckOnRefresh !== "boolean") {
|
|
144
|
+
return void errors.push(`app "${id}": recheckOnRefresh must be true or false`);
|
|
145
|
+
}
|
|
146
|
+
return { mode: "hook", ...value.recheckOnRefresh === true && { recheckOnRefresh: true } };
|
|
147
|
+
}
|
|
148
|
+
return void errors.push(`app "${id}": access.mode must be open | members | hook`);
|
|
149
|
+
}
|
|
150
|
+
function parseAppsConfig(value) {
|
|
151
|
+
const errors = [];
|
|
152
|
+
if (!isRecord(value) || Object.keys(value).length === 0) {
|
|
153
|
+
return { errors: ["apps must be a non-empty object of app id \u2192 definition"] };
|
|
154
|
+
}
|
|
155
|
+
const apps = {};
|
|
156
|
+
for (const [id, raw] of Object.entries(value)) {
|
|
157
|
+
if (!isRecord(raw)) {
|
|
158
|
+
errors.push(`app "${id}": definition must be an object`);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const extra = Object.keys(raw).filter((k) => !APP_KEYS.has(k));
|
|
162
|
+
if (extra.length > 0)
|
|
163
|
+
errors.push(`app "${id}": unknown field(s) ${extra.join(", ")}`);
|
|
164
|
+
const tenancy = parseTenancy(id, raw.tenancy, errors);
|
|
165
|
+
const access = parseAccess(id, raw.access, errors);
|
|
166
|
+
for (const key of ["audience", "cookieName"]) {
|
|
167
|
+
if (raw[key] !== void 0 && (typeof raw[key] !== "string" || raw[key] === "")) {
|
|
168
|
+
errors.push(`app "${id}": ${key} must be a non-empty string`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
if (raw.tokenStrategy !== void 0 && !STRATEGIES.has(raw.tokenStrategy)) {
|
|
172
|
+
errors.push(`app "${id}": tokenStrategy must be body | cookie | both`);
|
|
173
|
+
}
|
|
174
|
+
if (!tenancy || !access)
|
|
175
|
+
continue;
|
|
176
|
+
apps[id] = {
|
|
177
|
+
tenancy,
|
|
178
|
+
access,
|
|
179
|
+
...typeof raw.audience === "string" && { audience: raw.audience },
|
|
180
|
+
...typeof raw.cookieName === "string" && { cookieName: raw.cookieName },
|
|
181
|
+
...STRATEGIES.has(raw.tokenStrategy) && { tokenStrategy: raw.tokenStrategy }
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
return errors.length > 0 ? { errors } : { apps, errors };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// node_modules/.pnpm/ts-micro-result@3.3.0/node_modules/ts-micro-result/dist/core/freeze.js
|
|
188
|
+
var __DEV__ = typeof process !== "undefined" && process?.env?.NODE_ENV !== "production";
|
|
189
|
+
function freeze(obj) {
|
|
190
|
+
return __DEV__ ? Object.freeze(obj) : obj;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// node_modules/.pnpm/ts-micro-result@3.3.0/node_modules/ts-micro-result/dist/factories/ok.js
|
|
194
|
+
function ok(data, meta) {
|
|
195
|
+
if (arguments.length === 0) {
|
|
196
|
+
return freeze({
|
|
197
|
+
ok: true,
|
|
198
|
+
data: void 0
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
const result = {
|
|
202
|
+
ok: true,
|
|
203
|
+
data
|
|
204
|
+
};
|
|
205
|
+
if (meta !== void 0) {
|
|
206
|
+
result.meta = meta;
|
|
207
|
+
}
|
|
208
|
+
return freeze(result);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// node_modules/.pnpm/ts-micro-result@3.3.0/node_modules/ts-micro-result/dist/factories/err.js
|
|
212
|
+
function err(error, meta) {
|
|
213
|
+
const errors = freeze(Array.isArray(error) ? [...error] : [error]);
|
|
214
|
+
const result = {
|
|
215
|
+
ok: false,
|
|
216
|
+
errors
|
|
217
|
+
};
|
|
218
|
+
if (meta !== void 0) {
|
|
219
|
+
result.meta = meta;
|
|
220
|
+
}
|
|
221
|
+
return freeze(result);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// node_modules/.pnpm/ts-micro-result@3.3.0/node_modules/ts-micro-result/dist/factories/errors.js
|
|
225
|
+
function defineError(code, defaultMessage) {
|
|
226
|
+
return (params) => {
|
|
227
|
+
const error = {
|
|
228
|
+
code,
|
|
229
|
+
message: params?.message ?? defaultMessage
|
|
230
|
+
};
|
|
231
|
+
if (params?.field) {
|
|
232
|
+
error.field = params.field;
|
|
233
|
+
}
|
|
234
|
+
return error;
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
function defineErrorAdvanced(code, template) {
|
|
238
|
+
return (params) => {
|
|
239
|
+
let message = params?.message ?? template;
|
|
240
|
+
if (!params?.message && params) {
|
|
241
|
+
for (const key in params) {
|
|
242
|
+
if (key === "message" || key === "field")
|
|
243
|
+
continue;
|
|
244
|
+
const value = params[key];
|
|
245
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
246
|
+
message = message.replace(new RegExp(`\\{${key}\\}`, "g"), String(value));
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
const error = { code, message };
|
|
251
|
+
if (params?.field) {
|
|
252
|
+
error.field = params.field;
|
|
253
|
+
}
|
|
254
|
+
return error;
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// packages/auth-core/dist/core/common-errors.js
|
|
259
|
+
var commonErrors = {
|
|
260
|
+
// Validation errors
|
|
261
|
+
VALIDATION_ERROR: defineError("VALIDATION_ERROR", "D\u1EEF li\u1EC7u kh\xF4ng h\u1EE3p l\u1EC7"),
|
|
262
|
+
// Database errors
|
|
263
|
+
DATABASE_ERROR: defineError("DATABASE_ERROR", "L\u1ED7i c\u01A1 s\u1EDF d\u1EEF li\u1EC7u"),
|
|
264
|
+
// Authentication errors
|
|
265
|
+
UNAUTHORIZED: defineError("UNAUTHORIZED", "Kh\xF4ng c\xF3 quy\u1EC1n truy c\u1EADp"),
|
|
266
|
+
FORBIDDEN: defineError("FORBIDDEN", "B\u1ECB c\u1EA5m truy c\u1EADp"),
|
|
267
|
+
// Resource errors
|
|
268
|
+
NOT_FOUND: defineError("NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y t\xE0i nguy\xEAn"),
|
|
269
|
+
ALREADY_EXISTS: defineError("ALREADY_EXISTS", "T\xE0i nguy\xEAn \u0111\xE3 t\u1ED3n t\u1EA1i"),
|
|
270
|
+
// Rate limiting & blocking
|
|
271
|
+
RATE_LIMIT_EXCEEDED: defineError("RATE_LIMIT_EXCEEDED", "Qu\xE1 nhi\u1EC1u y\xEAu c\u1EA7u, vui l\xF2ng th\u1EED l\u1EA1i sau"),
|
|
272
|
+
ACCOUNT_SUSPENDED: defineError("ACCOUNT_SUSPENDED", "T\xE0i kho\u1EA3n \u0111\xE3 b\u1ECB t\u1EA1m ng\u01B0ng"),
|
|
273
|
+
ACCOUNT_DELETED: defineError("ACCOUNT_DELETED", "T\xE0i kho\u1EA3n \u0111\xE3 b\u1ECB x\xF3a"),
|
|
274
|
+
ACCOUNT_LOCKED: defineError("ACCOUNT_LOCKED", "T\xE0i kho\u1EA3n \u0111\xE3 b\u1ECB kh\xF3a"),
|
|
275
|
+
// System errors
|
|
276
|
+
INTERNAL_ERROR: defineError("INTERNAL_ERROR", "L\u1ED7i h\u1EC7 th\u1ED1ng, vui l\xF2ng th\u1EED l\u1EA1i sau"),
|
|
277
|
+
SERVICE_UNAVAILABLE: defineError("SERVICE_UNAVAILABLE", "D\u1ECBch v\u1EE5 t\u1EA1m th\u1EDDi kh\xF4ng kh\u1EA3 d\u1EE5ng"),
|
|
278
|
+
TIMEOUT: defineError("TIMEOUT", "Y\xEAu c\u1EA7u h\u1EBFt th\u1EDDi gian ch\u1EDD"),
|
|
279
|
+
// Network errors
|
|
280
|
+
NETWORK_ERROR: defineError("NETWORK_ERROR", "L\u1ED7i k\u1EBFt n\u1ED1i m\u1EA1ng"),
|
|
281
|
+
// Configuration errors
|
|
282
|
+
CONFIGURATION_ERROR: defineError("CONFIGURATION_ERROR", "L\u1ED7i c\u1EA5u h\xECnh h\u1EC7 th\u1ED1ng"),
|
|
283
|
+
// Plugin errors
|
|
284
|
+
PLUGIN_ERROR: defineError("PLUGIN_ERROR", "L\u1ED7i plugin"),
|
|
285
|
+
PLUGIN_NOT_FOUND: defineError("PLUGIN_NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y plugin"),
|
|
286
|
+
PLUGIN_INITIALIZATION_ERROR: defineError("PLUGIN_INITIALIZATION_ERROR", "L\u1ED7i kh\u1EDFi t\u1EA1o plugin")
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
// packages/auth-core/dist/core/security-settings.js
|
|
290
|
+
var DEFAULT_SECURITY_SETTINGS = {
|
|
291
|
+
// System tenant for audience-based authorization
|
|
292
|
+
systemTenantId: "__system__",
|
|
293
|
+
// Authentication protection
|
|
294
|
+
maxFailedAttempts: 5,
|
|
295
|
+
lockoutDurationMinutes: 30,
|
|
296
|
+
progressiveLockoutEnabled: true,
|
|
297
|
+
progressiveLockoutMultiplier: 2,
|
|
298
|
+
maxLockoutDurationMinutes: 1440,
|
|
299
|
+
// 24 giờ
|
|
300
|
+
// Session protection
|
|
301
|
+
maxConcurrentSessions: 5,
|
|
302
|
+
// Token protection
|
|
303
|
+
accessTokenLifetimeMinutes: 60,
|
|
304
|
+
// 1 giờ
|
|
305
|
+
refreshTokenLifetimeMinutes: 43200,
|
|
306
|
+
// 30 ngày
|
|
307
|
+
refreshTokenRotationEnabled: true,
|
|
308
|
+
verifySessionOnAuth: true,
|
|
309
|
+
refreshTokenGraceWindowMs: 1e4,
|
|
310
|
+
// 10 seconds grace window for concurrent refresh
|
|
311
|
+
// Password protection
|
|
312
|
+
passwordMinLength: 8,
|
|
313
|
+
requireSpecialChars: true,
|
|
314
|
+
requireUppercase: true,
|
|
315
|
+
requireLowercase: true,
|
|
316
|
+
requireNumbers: true,
|
|
317
|
+
// Verification code settings
|
|
318
|
+
maxVerificationCodeFailAttempts: 5,
|
|
319
|
+
// Số lần thử mã xác thực sai tối đa
|
|
320
|
+
verificationCodeExpiryMinutes: 10,
|
|
321
|
+
// Thời gian hết hạn mã xác thực (phút)
|
|
322
|
+
verificationResendCooldownSeconds: 60,
|
|
323
|
+
// Chống spam resend mã xác thực
|
|
324
|
+
// MFA protection (per-credential lockout)
|
|
325
|
+
maxMfaAttempts: 5,
|
|
326
|
+
// Max failed attempts per MFA credential
|
|
327
|
+
mfaCredentialLockoutDurationMinutes: 15,
|
|
328
|
+
// Shorter than account lockout for better UX
|
|
329
|
+
// Challenge protection
|
|
330
|
+
mfaChallengeExpiryMinutes: 5,
|
|
331
|
+
// MFA challenge expiry time (5 minutes)
|
|
332
|
+
maxChallengeAttempts: 3,
|
|
333
|
+
// Max verification attempts per challenge
|
|
334
|
+
stepUpWindowMinutes: 5,
|
|
335
|
+
securityNotificationsEnabled: true,
|
|
336
|
+
ownershipTransferEnabled: true,
|
|
337
|
+
// Tenant selection
|
|
338
|
+
tenantSelectionTokenLifetimeMinutes: 5,
|
|
339
|
+
// Tenant selection token expiry (5 minutes)
|
|
340
|
+
// Tenant invite settings
|
|
341
|
+
inviteExpirationMinutes: 10080,
|
|
342
|
+
// 7 days
|
|
343
|
+
maxPendingInvitesPerTenant: 100,
|
|
344
|
+
// Max pending invites per tenant
|
|
345
|
+
// Error response security
|
|
346
|
+
hideDetailedAuthErrors: true
|
|
347
|
+
// Hide detailed errors by default (security best practice)
|
|
348
|
+
};
|
|
349
|
+
function createSecuritySettings(overrides = {}) {
|
|
350
|
+
const settings = {
|
|
351
|
+
...DEFAULT_SECURITY_SETTINGS,
|
|
352
|
+
...overrides
|
|
353
|
+
};
|
|
354
|
+
if (overrides.accountLockDuration !== void 0 && overrides.lockoutDurationMinutes === void 0) {
|
|
355
|
+
settings.lockoutDurationMinutes = Math.floor(overrides.accountLockDuration / 6e4);
|
|
356
|
+
}
|
|
357
|
+
if (overrides.sessionDuration !== void 0 && overrides.refreshTokenLifetimeMinutes === void 0) {
|
|
358
|
+
settings.refreshTokenLifetimeMinutes = Math.floor(overrides.sessionDuration / 6e4);
|
|
359
|
+
}
|
|
360
|
+
if (overrides.allowMultipleSessions !== void 0 && overrides.maxConcurrentSessions === void 0) {
|
|
361
|
+
settings.maxConcurrentSessions = overrides.allowMultipleSessions ? 5 : 1;
|
|
362
|
+
}
|
|
363
|
+
return settings;
|
|
364
|
+
}
|
|
365
|
+
var SECURITY_PRESETS = {
|
|
366
|
+
// Bảo mật thấp - phù hợp cho development/testing
|
|
367
|
+
LOW: createSecuritySettings({
|
|
368
|
+
maxFailedAttempts: 10,
|
|
369
|
+
lockoutDurationMinutes: 5,
|
|
370
|
+
progressiveLockoutEnabled: false,
|
|
371
|
+
passwordMinLength: 6,
|
|
372
|
+
requireSpecialChars: false,
|
|
373
|
+
requireUppercase: false,
|
|
374
|
+
requireLowercase: false,
|
|
375
|
+
requireNumbers: false,
|
|
376
|
+
accessTokenLifetimeMinutes: 1440,
|
|
377
|
+
// 24 giờ
|
|
378
|
+
refreshTokenLifetimeMinutes: 129600,
|
|
379
|
+
// 90 ngày
|
|
380
|
+
refreshTokenGraceWindowMs: 3e4
|
|
381
|
+
// 30 seconds - more lenient for dev
|
|
382
|
+
}),
|
|
383
|
+
// Bảo mật trung bình - phù hợp cho production thông thường
|
|
384
|
+
MEDIUM: createSecuritySettings({
|
|
385
|
+
maxFailedAttempts: 5,
|
|
386
|
+
lockoutDurationMinutes: 30,
|
|
387
|
+
progressiveLockoutEnabled: true,
|
|
388
|
+
progressiveLockoutMultiplier: 2,
|
|
389
|
+
passwordMinLength: 8,
|
|
390
|
+
requireSpecialChars: true,
|
|
391
|
+
requireUppercase: true,
|
|
392
|
+
requireLowercase: true,
|
|
393
|
+
requireNumbers: true,
|
|
394
|
+
accessTokenLifetimeMinutes: 60,
|
|
395
|
+
// 1 giờ
|
|
396
|
+
refreshTokenLifetimeMinutes: 43200,
|
|
397
|
+
// 30 ngày
|
|
398
|
+
refreshTokenGraceWindowMs: 1e4
|
|
399
|
+
// 10 seconds - standard
|
|
400
|
+
}),
|
|
401
|
+
// Bảo mật cao - phù hợp cho banking, healthcare
|
|
402
|
+
HIGH: createSecuritySettings({
|
|
403
|
+
maxFailedAttempts: 3,
|
|
404
|
+
lockoutDurationMinutes: 60,
|
|
405
|
+
progressiveLockoutEnabled: true,
|
|
406
|
+
progressiveLockoutMultiplier: 3,
|
|
407
|
+
maxLockoutDurationMinutes: 2880,
|
|
408
|
+
// 48 giờ
|
|
409
|
+
maxConcurrentSessions: 2,
|
|
410
|
+
passwordMinLength: 12,
|
|
411
|
+
requireSpecialChars: true,
|
|
412
|
+
requireUppercase: true,
|
|
413
|
+
requireLowercase: true,
|
|
414
|
+
requireNumbers: true,
|
|
415
|
+
accessTokenLifetimeMinutes: 30,
|
|
416
|
+
// 30 phút
|
|
417
|
+
refreshTokenLifetimeMinutes: 10080,
|
|
418
|
+
// 7 ngày
|
|
419
|
+
refreshTokenGraceWindowMs: 5e3
|
|
420
|
+
// 5 seconds - tighter for high security
|
|
421
|
+
}),
|
|
422
|
+
// Bảo mật cực cao - phù hợp cho government, military
|
|
423
|
+
EXTREME: createSecuritySettings({
|
|
424
|
+
maxFailedAttempts: 2,
|
|
425
|
+
lockoutDurationMinutes: 120,
|
|
426
|
+
progressiveLockoutEnabled: true,
|
|
427
|
+
progressiveLockoutMultiplier: 4,
|
|
428
|
+
maxLockoutDurationMinutes: 10080,
|
|
429
|
+
// 1 tuần
|
|
430
|
+
maxConcurrentSessions: 1,
|
|
431
|
+
passwordMinLength: 16,
|
|
432
|
+
requireSpecialChars: true,
|
|
433
|
+
requireUppercase: true,
|
|
434
|
+
requireLowercase: true,
|
|
435
|
+
requireNumbers: true,
|
|
436
|
+
accessTokenLifetimeMinutes: 15,
|
|
437
|
+
// 15 phút
|
|
438
|
+
refreshTokenLifetimeMinutes: 1440,
|
|
439
|
+
// 1 ngày
|
|
440
|
+
refreshTokenGraceWindowMs: 3e3
|
|
441
|
+
// 3 seconds - minimal for extreme security
|
|
442
|
+
})
|
|
443
|
+
};
|
|
444
|
+
|
|
445
|
+
// packages/auth-core/dist/features/authentication/app-errors.js
|
|
446
|
+
var appErrors = {
|
|
447
|
+
/** The request names an app this deployment does not configure. */
|
|
448
|
+
APP_UNKNOWN: defineError("APP_UNKNOWN", "Unknown app"),
|
|
449
|
+
/** The request is for a different app than the session or challenge it carries. */
|
|
450
|
+
APP_MISMATCH: defineError("APP_MISMATCH", "This session belongs to another app"),
|
|
451
|
+
/** The request names two different apps (its path and its X-Auth-Context header). */
|
|
452
|
+
APP_CONFLICT: defineError("APP_CONFLICT", "The request names two different apps"),
|
|
453
|
+
/** An access token of one app used on a request for another app. */
|
|
454
|
+
TOKEN_APP_MISMATCH: defineError("TOKEN_APP_MISMATCH", "This token belongs to another app"),
|
|
455
|
+
/** The session's app does not allow switching into this tenant. */
|
|
456
|
+
TENANT_NOT_SELECTABLE: defineError("TENANT_NOT_SELECTABLE", "This tenant cannot be selected in this app"),
|
|
457
|
+
/** The app's access hook said no (or failed: it is fail-closed). */
|
|
458
|
+
ACCESS_DENIED: defineError("APP_ACCESS_DENIED", "Access to this app is denied"),
|
|
459
|
+
/** On refresh: the user is no longer an active member of the session's tenant. */
|
|
460
|
+
ACCESS_REVOKED: defineError("ACCESS_REVOKED", "Access to this tenant was revoked")
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
// packages/auth-core/dist/features/authentication/credential-proof.js
|
|
464
|
+
var credentialProofErrors = {
|
|
465
|
+
STALE: defineError("INVALID_CREDENTIALS", "Invalid credentials")
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
// packages/auth-core/dist/features/authentication/get-current-user/errors.js
|
|
469
|
+
var getCurrentUserErrors = {
|
|
470
|
+
USER_NOT_FOUND: defineError("USER_NOT_FOUND", "User not found")
|
|
471
|
+
};
|
|
472
|
+
|
|
473
|
+
// packages/auth-core/dist/entities/identity.js
|
|
474
|
+
var IDENTITY_TYPE = {
|
|
475
|
+
EMAIL: "email",
|
|
476
|
+
PHONE: "phone",
|
|
477
|
+
USERNAME: "username",
|
|
478
|
+
WALLET: "wallet"
|
|
479
|
+
};
|
|
480
|
+
|
|
481
|
+
// packages/auth-core/dist/features/authentication/logout/errors.js
|
|
482
|
+
var logoutErrors = {
|
|
483
|
+
// Scope validation errors
|
|
484
|
+
SCOPE_MISMATCH: defineError("SCOPE_MISMATCH", "Token scope does not match route scope"),
|
|
485
|
+
// Reuse common errors
|
|
486
|
+
DATABASE_ERROR: commonErrors.DATABASE_ERROR
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
// packages/auth-core/dist/features/authentication/refresh-token/errors.js
|
|
490
|
+
var refreshTokenErrors = {
|
|
491
|
+
// Token validation errors
|
|
492
|
+
INVALID_TOKEN: defineError("INVALID_TOKEN", "Token kh\xF4ng h\u1EE3p l\u1EC7"),
|
|
493
|
+
// Scope validation errors
|
|
494
|
+
SCOPE_MISMATCH: defineError("SCOPE_MISMATCH", "Token scope does not match route scope"),
|
|
495
|
+
// Account status errors (for early rejection in refresh flow)
|
|
496
|
+
ACCOUNT_LOCKED: defineError("ACCOUNT_LOCKED", "T\xE0i kho\u1EA3n t\u1EA1m th\u1EDDi b\u1ECB kh\xF3a"),
|
|
497
|
+
TOKEN_ROTATED: defineError("TOKEN_ROTATED", "Token \u0111\xE3 \u0111\u01B0\u1EE3c xoay v\xF2ng, vui l\xF2ng \u0111\u0103ng nh\u1EADp l\u1EA1i"),
|
|
498
|
+
// Reuse common errors
|
|
499
|
+
VALIDATION_ERROR: commonErrors.VALIDATION_ERROR,
|
|
500
|
+
DATABASE_ERROR: commonErrors.DATABASE_ERROR,
|
|
501
|
+
INTERNAL_ERROR: commonErrors.INTERNAL_ERROR,
|
|
502
|
+
ACCOUNT_SUSPENDED: commonErrors.ACCOUNT_SUSPENDED,
|
|
503
|
+
ACCOUNT_DELETED: commonErrors.ACCOUNT_DELETED
|
|
504
|
+
};
|
|
505
|
+
|
|
506
|
+
// packages/auth-core/dist/types/jwt.js
|
|
507
|
+
var TokenType;
|
|
508
|
+
(function(TokenType2) {
|
|
509
|
+
TokenType2[TokenType2["Access"] = 1] = "Access";
|
|
510
|
+
TokenType2[TokenType2["Refresh"] = 2] = "Refresh";
|
|
511
|
+
TokenType2[TokenType2["Service"] = 3] = "Service";
|
|
512
|
+
})(TokenType || (TokenType = {}));
|
|
513
|
+
|
|
514
|
+
// packages/auth-core/dist/features/authentication/authenticate/errors.js
|
|
515
|
+
var authenticateErrors = {
|
|
516
|
+
/**
|
|
517
|
+
* Identity plugin not found
|
|
518
|
+
*/
|
|
519
|
+
IDENTITY_PLUGIN_NOT_FOUND: defineErrorAdvanced("IDENTITY_PLUGIN_NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y plugin x\xE1c th\u1EF1c cho lo\u1EA1i \u0111\u1ECBnh danh {identityType}"),
|
|
520
|
+
/**
|
|
521
|
+
* Credential plugin not found
|
|
522
|
+
*/
|
|
523
|
+
CREDENTIAL_PLUGIN_NOT_FOUND: defineErrorAdvanced("CREDENTIAL_PLUGIN_NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y plugin x\xE1c th\u1EF1c cho lo\u1EA1i th\xF4ng tin x\xE1c th\u1EF1c {credentialType}"),
|
|
524
|
+
/**
|
|
525
|
+
* Login disabled for identity
|
|
526
|
+
*/
|
|
527
|
+
LOGIN_DISABLED: defineError("LOGIN_DISABLED", "\u0110\u0103ng nh\u1EADp \u0111\xE3 b\u1ECB v\xF4 hi\u1EC7u h\xF3a cho \u0111\u1ECBnh danh n\xE0y"),
|
|
528
|
+
/**
|
|
529
|
+
* Identity not verified
|
|
530
|
+
*/
|
|
531
|
+
IDENTITY_NOT_VERIFIED: defineError("IDENTITY_NOT_VERIFIED", "Vui l\xF2ng x\xE1c minh \u0111\u1ECBnh danh tr\u01B0\u1EDBc khi \u0111\u0103ng nh\u1EADp"),
|
|
532
|
+
/**
|
|
533
|
+
* Verification email cooldown active
|
|
534
|
+
*/
|
|
535
|
+
VERIFICATION_COOLDOWN_ACTIVE: defineError("VERIFICATION_COOLDOWN_ACTIVE", "Vui l\xF2ng ch\u1EDD tr\u01B0\u1EDBc khi y\xEAu c\u1EA7u g\u1EEDi l\u1EA1i email x\xE1c minh"),
|
|
536
|
+
/**
|
|
537
|
+
* Guard locked (too many failed attempts)
|
|
538
|
+
*/
|
|
539
|
+
GUARD_LOCKED: defineErrorAdvanced("GUARD_LOCKED", "Ph\u01B0\u01A1ng th\u1EE9c \u0111\u0103ng nh\u1EADp t\u1EA1m th\u1EDDi b\u1ECB kh\xF3a do qu\xE1 nhi\u1EC1u l\u1EA7n th\u1EED sai. Vui l\xF2ng th\u1EED l\u1EA1i sau {minutes} ph\xFAt"),
|
|
540
|
+
/**
|
|
541
|
+
* Invalid credentials (generic error for security)
|
|
542
|
+
*/
|
|
543
|
+
INVALID_CREDENTIALS: defineError("INVALID_CREDENTIALS", "Th\xF4ng tin \u0111\u0103ng nh\u1EADp kh\xF4ng h\u1EE3p l\u1EC7"),
|
|
544
|
+
/**
|
|
545
|
+
* User auth not found (data integrity issue)
|
|
546
|
+
*/
|
|
547
|
+
USER_AUTH_NOT_FOUND: defineError("USER_AUTH_NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y b\u1EA3n ghi x\xE1c th\u1EF1c ng\u01B0\u1EDDi d\xF9ng"),
|
|
548
|
+
/**
|
|
549
|
+
* Account suspended
|
|
550
|
+
*/
|
|
551
|
+
ACCOUNT_SUSPENDED: defineError("ACCOUNT_SUSPENDED", "T\xE0i kho\u1EA3n n\xE0y \u0111\xE3 b\u1ECB t\u1EA1m ng\u01B0ng"),
|
|
552
|
+
/**
|
|
553
|
+
* MFA plugin not found
|
|
554
|
+
*/
|
|
555
|
+
MFA_PLUGIN_NOT_FOUND: defineError("MFA_PLUGIN_NOT_FOUND", "Ch\u01B0a c\u1EA5u h\xECnh plugin x\xE1c th\u1EF1c \u0111a y\u1EBFu t\u1ED1 (MFA)"),
|
|
556
|
+
/**
|
|
557
|
+
* Invalid identity format
|
|
558
|
+
*/
|
|
559
|
+
INVALID_IDENTITY_FORMAT: defineError("INVALID_IDENTITY_FORMAT", "\u0110\u1ECBnh d\u1EA1ng \u0111\u1ECBnh danh kh\xF4ng h\u1EE3p l\u1EC7"),
|
|
560
|
+
/**
|
|
561
|
+
* No access to tenant (multi-tenant)
|
|
562
|
+
*/
|
|
563
|
+
NO_ACCESS_TO_TENANT: defineErrorAdvanced("NO_ACCESS_TO_TENANT", "Ng\u01B0\u1EDDi d\xF9ng kh\xF4ng ph\u1EA3i l\xE0 th\xE0nh vi\xEAn c\u1EE7a tenant {tenantId}"),
|
|
564
|
+
/**
|
|
565
|
+
* Suspended in tenant (multi-tenant)
|
|
566
|
+
*/
|
|
567
|
+
SUSPENDED_IN_TENANT: defineErrorAdvanced("SUSPENDED_IN_TENANT", "Ng\u01B0\u1EDDi d\xF9ng b\u1ECB {status} trong tenant {tenantId}"),
|
|
568
|
+
/**
|
|
569
|
+
* Challenge creation failed
|
|
570
|
+
*/
|
|
571
|
+
CHALLENGE_CREATE_FAILED: defineError("CHALLENGE_CREATE_FAILED", "Kh\xF4ng th\u1EC3 t\u1EA1o challenge x\xE1c th\u1EF1c"),
|
|
572
|
+
/**
|
|
573
|
+
* Session creation failed
|
|
574
|
+
*/
|
|
575
|
+
SESSION_CREATE_FAILED: defineError("SESSION_CREATE_FAILED", "Kh\xF4ng th\u1EC3 t\u1EA1o phi\xEAn \u0111\u0103ng nh\u1EADp"),
|
|
576
|
+
/**
|
|
577
|
+
* Token generation failed
|
|
578
|
+
*/
|
|
579
|
+
TOKEN_GENERATION_FAILED: defineError("TOKEN_GENERATION_FAILED", "Kh\xF4ng th\u1EC3 t\u1EA1o token x\xE1c th\u1EF1c"),
|
|
580
|
+
/**
|
|
581
|
+
* User context not found (multi-tenant)
|
|
582
|
+
*/
|
|
583
|
+
USER_CONTEXT_NOT_FOUND: defineErrorAdvanced("USER_CONTEXT_NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y ng\u1EEF c\u1EA3nh ng\u01B0\u1EDDi d\xF9ng cho tenant {tenantId}"),
|
|
584
|
+
// Reuse common errors
|
|
585
|
+
VALIDATION_ERROR: commonErrors.VALIDATION_ERROR,
|
|
586
|
+
DATABASE_ERROR: commonErrors.DATABASE_ERROR,
|
|
587
|
+
INTERNAL_ERROR: commonErrors.INTERNAL_ERROR,
|
|
588
|
+
ACCOUNT_DELETED: commonErrors.ACCOUNT_DELETED
|
|
589
|
+
};
|
|
590
|
+
|
|
591
|
+
// packages/auth-core/dist/entities/challenge.js
|
|
592
|
+
var CHALLENGE_PURPOSE = {
|
|
593
|
+
LOGIN: "login",
|
|
594
|
+
REGISTRATION: "registration",
|
|
595
|
+
PASSWORD_RESET: "password-reset",
|
|
596
|
+
EMAIL_VERIFICATION: "email-verification",
|
|
597
|
+
PHONE_VERIFICATION: "phone-verification",
|
|
598
|
+
STEP_UP: "step-up"
|
|
599
|
+
};
|
|
600
|
+
|
|
601
|
+
// packages/auth-core/dist/plugins/credential-plugin.js
|
|
602
|
+
var credentialPluginErrors = {
|
|
603
|
+
SERVICE_UNAVAILABLE: defineError("CREDENTIAL_SERVICE_UNAVAILABLE", "Credential check is temporarily unavailable, please try again")
|
|
604
|
+
};
|
|
605
|
+
|
|
606
|
+
// packages/auth-core/dist/types/email-models.js
|
|
607
|
+
var EMAIL_TEMPLATES = {
|
|
608
|
+
EMAIL_VERIFICATION: "email-verification",
|
|
609
|
+
PASSWORD_RESET: "password-reset",
|
|
610
|
+
LOGIN_OTP: "login-otp",
|
|
611
|
+
MFA_EMAIL_CODE: "mfa-email-code",
|
|
612
|
+
STEP_UP_CODE: "step-up-code",
|
|
613
|
+
/** Notice of a sign-in change (no code); variables: `event`, `occurredAt`, optional details. */
|
|
614
|
+
SECURITY_ALERT: "security-alert"
|
|
615
|
+
};
|
|
616
|
+
|
|
617
|
+
// packages/auth-core/dist/features/user-management/verification/sdk-deps.js
|
|
618
|
+
var VERIFICATION_CHANNEL = {
|
|
619
|
+
SMS: "sms",
|
|
620
|
+
EMAIL: "email"
|
|
621
|
+
};
|
|
622
|
+
var IDENTITY_TYPE2 = {
|
|
623
|
+
PHONE: "phone",
|
|
624
|
+
EMAIL: "email"
|
|
625
|
+
};
|
|
626
|
+
var VERIFICATION_TEMPLATE = {
|
|
627
|
+
SMS_CODE: "verification-code",
|
|
628
|
+
EMAIL_CODE: EMAIL_TEMPLATES.EMAIL_VERIFICATION
|
|
629
|
+
};
|
|
630
|
+
|
|
631
|
+
// packages/auth-core/dist/features/user-management/verification/channels/email.js
|
|
632
|
+
var emailChannel = {
|
|
633
|
+
type: VERIFICATION_CHANNEL.EMAIL,
|
|
634
|
+
purpose: CHALLENGE_PURPOSE.EMAIL_VERIFICATION,
|
|
635
|
+
identityType: IDENTITY_TYPE2.EMAIL,
|
|
636
|
+
template: VERIFICATION_TEMPLATE.EMAIL_CODE
|
|
637
|
+
};
|
|
638
|
+
|
|
639
|
+
// packages/auth-core/dist/features/user-management/verification/channels/sms.js
|
|
640
|
+
var smsChannel = {
|
|
641
|
+
type: VERIFICATION_CHANNEL.SMS,
|
|
642
|
+
purpose: CHALLENGE_PURPOSE.PHONE_VERIFICATION,
|
|
643
|
+
identityType: IDENTITY_TYPE2.PHONE,
|
|
644
|
+
template: VERIFICATION_TEMPLATE.SMS_CODE
|
|
645
|
+
};
|
|
646
|
+
|
|
647
|
+
// packages/auth-core/dist/features/user-management/verification/errors.js
|
|
648
|
+
var verificationErrors = {
|
|
649
|
+
// ========================================
|
|
650
|
+
// Channel Errors
|
|
651
|
+
// ========================================
|
|
652
|
+
CHANNEL_NOT_CONFIGURED: defineError("CHANNEL_NOT_CONFIGURED", "Verification channel is not configured"),
|
|
653
|
+
SEND_ERROR: defineError("SEND_ERROR", "Failed to send verification code"),
|
|
654
|
+
// ========================================
|
|
655
|
+
// Identity Errors
|
|
656
|
+
// ========================================
|
|
657
|
+
IDENTITY_NOT_FOUND: defineError("IDENTITY_NOT_FOUND", "Identity not found"),
|
|
658
|
+
USER_NOT_FOUND: defineError("USER_NOT_FOUND", "User not found"),
|
|
659
|
+
IDENTITY_ALREADY_VERIFIED: defineError("IDENTITY_ALREADY_VERIFIED", "Identity is already verified"),
|
|
660
|
+
// ========================================
|
|
661
|
+
// Challenge Errors
|
|
662
|
+
// ========================================
|
|
663
|
+
CHALLENGE_NOT_FOUND: defineError("CHALLENGE_NOT_FOUND", "Verification challenge not found"),
|
|
664
|
+
CHALLENGE_EXPIRED: defineError("CHALLENGE_EXPIRED", "Verification challenge has expired"),
|
|
665
|
+
CHALLENGE_ALREADY_USED: defineError("CHALLENGE_ALREADY_USED", "Verification challenge has already been used"),
|
|
666
|
+
PREVIOUS_CHALLENGE_REQUIRED: defineError("PREVIOUS_CHALLENGE_REQUIRED", "Previous verification challenge is required to resend a code"),
|
|
667
|
+
RESEND_COOLDOWN_ACTIVE: defineError("RESEND_COOLDOWN_ACTIVE", "Please wait before requesting another verification code"),
|
|
668
|
+
VERIFICATION_COOLDOWN_ACTIVE: defineError("VERIFICATION_COOLDOWN_ACTIVE", "Please wait before requesting a new verification code"),
|
|
669
|
+
// ========================================
|
|
670
|
+
// Code Verification Errors
|
|
671
|
+
// ========================================
|
|
672
|
+
INVALID_CODE: defineError("INVALID_CODE", "Invalid verification code"),
|
|
673
|
+
CODE_EXPIRED: defineError("CODE_EXPIRED", "Verification code has expired"),
|
|
674
|
+
TOO_MANY_ATTEMPTS: defineError("TOO_MANY_ATTEMPTS", "Too many failed attempts. Please request a new code"),
|
|
675
|
+
// ========================================
|
|
676
|
+
// Auth Scope Errors
|
|
677
|
+
// ========================================
|
|
678
|
+
AUTH_SCOPE_MISMATCH: defineError("AUTH_SCOPE_MISMATCH", "Route auth scope does not match challenge scope")
|
|
679
|
+
};
|
|
680
|
+
|
|
681
|
+
// packages/auth-core/dist/features/user-management/verification/verify-code/usecase.js
|
|
682
|
+
var VERIFICATION_PURPOSES = [CHALLENGE_PURPOSE.PHONE_VERIFICATION, CHALLENGE_PURPOSE.EMAIL_VERIFICATION];
|
|
683
|
+
|
|
684
|
+
// packages/auth-core/dist/features/authentication/check-mfa-requirement.js
|
|
685
|
+
var checkMfaRequirementErrors = {
|
|
686
|
+
MFA_UNAVAILABLE: defineError("MFA_UNAVAILABLE", "Required MFA is unavailable"),
|
|
687
|
+
CHALLENGE_CREATE_FAILED: defineError("CHALLENGE_CREATE_FAILED", "Failed to create MFA challenge")
|
|
688
|
+
};
|
|
689
|
+
|
|
690
|
+
// packages/auth-core/dist/features/authentication/validate-user-access.js
|
|
691
|
+
var ValidateUserAccessErrorCodes = {
|
|
692
|
+
ACCOUNT_DELETED: "ACCOUNT_DELETED",
|
|
693
|
+
ACCOUNT_SUSPENDED: "ACCOUNT_SUSPENDED",
|
|
694
|
+
NO_ACCESS_TO_TENANT: "NO_ACCESS_TO_TENANT",
|
|
695
|
+
SUSPENDED_IN_TENANT: "SUSPENDED_IN_TENANT"
|
|
696
|
+
};
|
|
697
|
+
var validateUserAccessErrors = {
|
|
698
|
+
/**
|
|
699
|
+
* Account deleted
|
|
700
|
+
*/
|
|
701
|
+
ACCOUNT_DELETED: commonErrors.ACCOUNT_DELETED,
|
|
702
|
+
/**
|
|
703
|
+
* Account suspended
|
|
704
|
+
*/
|
|
705
|
+
ACCOUNT_SUSPENDED: defineError(ValidateUserAccessErrorCodes.ACCOUNT_SUSPENDED, "T\xE0i kho\u1EA3n n\xE0y \u0111\xE3 b\u1ECB t\u1EA1m ng\u01B0ng"),
|
|
706
|
+
/**
|
|
707
|
+
* No access to tenant
|
|
708
|
+
*/
|
|
709
|
+
NO_ACCESS_TO_TENANT: defineError(ValidateUserAccessErrorCodes.NO_ACCESS_TO_TENANT, "B\u1EA1n kh\xF4ng c\xF3 quy\u1EC1n truy c\u1EADp v\xE0o tenant n\xE0y"),
|
|
710
|
+
/**
|
|
711
|
+
* Suspended in tenant
|
|
712
|
+
*/
|
|
713
|
+
SUSPENDED_IN_TENANT: defineError(ValidateUserAccessErrorCodes.SUSPENDED_IN_TENANT, "T\xE0i kho\u1EA3n c\u1EE7a b\u1EA1n \u0111\xE3 b\u1ECB t\u1EA1m ng\u01B0ng trong tenant n\xE0y")
|
|
714
|
+
};
|
|
715
|
+
|
|
716
|
+
// packages/auth-core/dist/features/authentication/complete-credential-challenge/errors.js
|
|
717
|
+
var completeChallengeErrors = {
|
|
718
|
+
/**
|
|
719
|
+
* Challenge not found
|
|
720
|
+
*/
|
|
721
|
+
CHALLENGE_NOT_FOUND: defineError("CHALLENGE_NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y th\u1EED th\xE1ch ho\u1EB7c \u0111\xE3 ho\xE0n th\xE0nh"),
|
|
722
|
+
/**
|
|
723
|
+
* Challenge expired
|
|
724
|
+
*/
|
|
725
|
+
CHALLENGE_EXPIRED: defineError("CHALLENGE_EXPIRED", "Th\u1EED th\xE1ch \u0111\xE3 h\u1EBFt h\u1EA1n. Vui l\xF2ng y\xEAu c\u1EA7u m\u1ED9t th\u1EED th\xE1ch m\u1EDBi"),
|
|
726
|
+
/**
|
|
727
|
+
* Invalid challenge state/phase
|
|
728
|
+
*/
|
|
729
|
+
INVALID_CHALLENGE_STATE: defineError("INVALID_CHALLENGE_STATE", "Th\u1EED th\xE1ch kh\xF4ng \u1EDF tr\u1EA1ng th\xE1i h\u1EE3p l\u1EC7 \u0111\u1EC3 ho\xE0n th\xE0nh"),
|
|
730
|
+
/**
|
|
731
|
+
* Invalid challenge code
|
|
732
|
+
*/
|
|
733
|
+
INVALID_CHALLENGE_CODE: defineError("INVALID_CHALLENGE_CODE", "M\xE3 x\xE1c minh kh\xF4ng h\u1EE3p l\u1EC7"),
|
|
734
|
+
/**
|
|
735
|
+
* Max attempts exceeded
|
|
736
|
+
*/
|
|
737
|
+
MAX_ATTEMPTS_EXCEEDED: defineError("MAX_ATTEMPTS_EXCEEDED", "\u0110\xE3 v\u01B0\u1EE3t qu\xE1 s\u1ED1 l\u1EA7n th\u1EED t\u1ED1i \u0111a. Th\u1EED th\xE1ch \u0111\xE3 b\u1ECB kh\xF3a"),
|
|
738
|
+
/**
|
|
739
|
+
* User auth not found
|
|
740
|
+
*/
|
|
741
|
+
USER_AUTH_NOT_FOUND: defineError("USER_AUTH_NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y b\u1EA3n ghi x\xE1c th\u1EF1c ng\u01B0\u1EDDi d\xF9ng"),
|
|
742
|
+
/**
|
|
743
|
+
* Account suspended
|
|
744
|
+
*/
|
|
745
|
+
ACCOUNT_SUSPENDED: defineError("ACCOUNT_SUSPENDED", "T\xE0i kho\u1EA3n n\xE0y \u0111\xE3 b\u1ECB t\u1EA1m ng\u01B0ng"),
|
|
746
|
+
/**
|
|
747
|
+
* MFA plugin not found
|
|
748
|
+
*/
|
|
749
|
+
MFA_PLUGIN_NOT_FOUND: defineError("MFA_PLUGIN_NOT_FOUND", "Ch\u01B0a c\u1EA5u h\xECnh plugin x\xE1c th\u1EF1c \u0111a y\u1EBFu t\u1ED1 (MFA)"),
|
|
750
|
+
/**
|
|
751
|
+
* Challenge scope does not match route scope
|
|
752
|
+
*/
|
|
753
|
+
SCOPE_MISMATCH: defineError("SCOPE_MISMATCH", "Challenge scope does not match route scope"),
|
|
754
|
+
/**
|
|
755
|
+
* No access to tenant
|
|
756
|
+
*/
|
|
757
|
+
NO_ACCESS_TO_TENANT: defineError("NO_ACCESS_TO_TENANT", "B\u1EA1n kh\xF4ng c\xF3 quy\u1EC1n truy c\u1EADp v\xE0o tenant n\xE0y"),
|
|
758
|
+
/**
|
|
759
|
+
* Suspended in tenant
|
|
760
|
+
*/
|
|
761
|
+
SUSPENDED_IN_TENANT: defineError("SUSPENDED_IN_TENANT", "T\xE0i kho\u1EA3n c\u1EE7a b\u1EA1n \u0111\xE3 b\u1ECB t\u1EA1m ng\u01B0ng trong tenant n\xE0y"),
|
|
762
|
+
// Reuse common errors
|
|
763
|
+
VALIDATION_ERROR: commonErrors.VALIDATION_ERROR,
|
|
764
|
+
DATABASE_ERROR: commonErrors.DATABASE_ERROR,
|
|
765
|
+
INTERNAL_ERROR: commonErrors.INTERNAL_ERROR
|
|
766
|
+
};
|
|
767
|
+
|
|
768
|
+
// packages/auth-core/dist/features/authentication/complete-mfa-challenge/errors.js
|
|
769
|
+
var completeMfaChallengeErrors = {
|
|
770
|
+
/**
|
|
771
|
+
* MFA challenge not found
|
|
772
|
+
*/
|
|
773
|
+
MFA_CHALLENGE_NOT_FOUND: defineError("MFA_CHALLENGE_NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y th\u1EED th\xE1ch MFA ho\u1EB7c \u0111\xE3 ho\xE0n th\xE0nh"),
|
|
774
|
+
/**
|
|
775
|
+
* MFA challenge expired
|
|
776
|
+
*/
|
|
777
|
+
MFA_CHALLENGE_EXPIRED: defineError("MFA_CHALLENGE_EXPIRED", "Th\u1EED th\xE1ch MFA \u0111\xE3 h\u1EBFt h\u1EA1n. Vui l\xF2ng y\xEAu c\u1EA7u m\u1ED9t th\u1EED th\xE1ch m\u1EDBi"),
|
|
778
|
+
/**
|
|
779
|
+
* Invalid challenge state/phase
|
|
780
|
+
*/
|
|
781
|
+
INVALID_CHALLENGE_STATE: defineError("INVALID_CHALLENGE_STATE", "Th\u1EED th\xE1ch MFA kh\xF4ng \u1EDF tr\u1EA1ng th\xE1i h\u1EE3p l\u1EC7 \u0111\u1EC3 ho\xE0n th\xE0nh"),
|
|
782
|
+
/**
|
|
783
|
+
* Invalid MFA code
|
|
784
|
+
*/
|
|
785
|
+
INVALID_MFA_CODE: defineError("INVALID_MFA_CODE", "M\xE3 MFA kh\xF4ng h\u1EE3p l\u1EC7"),
|
|
786
|
+
/**
|
|
787
|
+
* Too many failed MFA attempts on this challenge
|
|
788
|
+
*/
|
|
789
|
+
TOO_MANY_ATTEMPTS: defineError("TOO_MANY_ATTEMPTS", "Qu\xE1 nhi\u1EC1u l\u1EA7n th\u1EED m\xE3 MFA, vui l\xF2ng \u0111\u0103ng nh\u1EADp l\u1EA1i"),
|
|
790
|
+
/**
|
|
791
|
+
* MFA method not supported
|
|
792
|
+
*/
|
|
793
|
+
MFA_METHOD_NOT_SUPPORTED: defineError("MFA_METHOD_NOT_SUPPORTED", "Ph\u01B0\u01A1ng th\u1EE9c MFA kh\xF4ng \u0111\u01B0\u1EE3c h\u1ED7 tr\u1EE3 cho ng\u01B0\u1EDDi d\xF9ng n\xE0y"),
|
|
794
|
+
/**
|
|
795
|
+
* User auth not found
|
|
796
|
+
*/
|
|
797
|
+
USER_AUTH_NOT_FOUND: defineError("USER_AUTH_NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y b\u1EA3n ghi x\xE1c th\u1EF1c ng\u01B0\u1EDDi d\xF9ng"),
|
|
798
|
+
/**
|
|
799
|
+
* Account suspended
|
|
800
|
+
*/
|
|
801
|
+
ACCOUNT_SUSPENDED: defineError("ACCOUNT_SUSPENDED", "T\xE0i kho\u1EA3n n\xE0y \u0111\xE3 b\u1ECB t\u1EA1m ng\u01B0ng"),
|
|
802
|
+
/**
|
|
803
|
+
* MFA plugin not found
|
|
804
|
+
*/
|
|
805
|
+
MFA_PLUGIN_NOT_FOUND: defineError("MFA_PLUGIN_NOT_FOUND", "Ch\u01B0a c\u1EA5u h\xECnh plugin x\xE1c th\u1EF1c \u0111a y\u1EBFu t\u1ED1 (MFA)"),
|
|
806
|
+
/**
|
|
807
|
+
* Challenge scope does not match route scope
|
|
808
|
+
*/
|
|
809
|
+
SCOPE_MISMATCH: defineError("SCOPE_MISMATCH", "Challenge scope does not match route scope"),
|
|
810
|
+
/**
|
|
811
|
+
* No access to tenant
|
|
812
|
+
*/
|
|
813
|
+
NO_ACCESS_TO_TENANT: defineError("NO_ACCESS_TO_TENANT", "B\u1EA1n kh\xF4ng c\xF3 quy\u1EC1n truy c\u1EADp v\xE0o tenant n\xE0y"),
|
|
814
|
+
/**
|
|
815
|
+
* Suspended in tenant
|
|
816
|
+
*/
|
|
817
|
+
SUSPENDED_IN_TENANT: defineError("SUSPENDED_IN_TENANT", "T\xE0i kho\u1EA3n c\u1EE7a b\u1EA1n \u0111\xE3 b\u1ECB t\u1EA1m ng\u01B0ng trong tenant n\xE0y"),
|
|
818
|
+
// Reuse common errors
|
|
819
|
+
VALIDATION_ERROR: commonErrors.VALIDATION_ERROR,
|
|
820
|
+
DATABASE_ERROR: commonErrors.DATABASE_ERROR,
|
|
821
|
+
INTERNAL_ERROR: commonErrors.INTERNAL_ERROR
|
|
822
|
+
};
|
|
823
|
+
|
|
824
|
+
// packages/auth-core/dist/features/authentication/issue-mfa-challenge/errors.js
|
|
825
|
+
var issueMfaChallengeErrors = {
|
|
826
|
+
/**
|
|
827
|
+
* Challenge not found
|
|
828
|
+
*/
|
|
829
|
+
CHALLENGE_NOT_FOUND: defineError("CHALLENGE_NOT_FOUND", "Challenge kh\xF4ng t\u1ED3n t\u1EA1i"),
|
|
830
|
+
/**
|
|
831
|
+
* Challenge expired
|
|
832
|
+
*/
|
|
833
|
+
CHALLENGE_EXPIRED: defineError("CHALLENGE_EXPIRED", "Challenge \u0111\xE3 h\u1EBFt h\u1EA1n"),
|
|
834
|
+
/**
|
|
835
|
+
* Challenge invalid status
|
|
836
|
+
*/
|
|
837
|
+
CHALLENGE_INVALID_STATUS: defineErrorAdvanced("CHALLENGE_INVALID_STATUS", "Challenge c\xF3 tr\u1EA1ng th\xE1i kh\xF4ng h\u1EE3p l\u1EC7: {status}"),
|
|
838
|
+
/**
|
|
839
|
+
* Method not allowed
|
|
840
|
+
*/
|
|
841
|
+
METHOD_NOT_ALLOWED: defineErrorAdvanced("METHOD_NOT_ALLOWED", "Ph\u01B0\u01A1ng th\u1EE9c {method} kh\xF4ng \u0111\u01B0\u1EE3c ph\xE9p cho challenge n\xE0y"),
|
|
842
|
+
/**
|
|
843
|
+
* Method does not require server delivery
|
|
844
|
+
*/
|
|
845
|
+
METHOD_NO_SERVER_DELIVERY: defineErrorAdvanced("METHOD_NO_SERVER_DELIVERY", "Ph\u01B0\u01A1ng th\u1EE9c {method} kh\xF4ng c\u1EA7n server g\u1EEDi m\xE3"),
|
|
846
|
+
/**
|
|
847
|
+
* MFA plugin not found
|
|
848
|
+
*/
|
|
849
|
+
MFA_PLUGIN_NOT_FOUND: defineErrorAdvanced("MFA_PLUGIN_NOT_FOUND", "Kh\xF4ng t\xECm th\u1EA5y plugin MFA cho ph\u01B0\u01A1ng th\u1EE9c {method}"),
|
|
850
|
+
/**
|
|
851
|
+
* Challenge issue failed
|
|
852
|
+
*/
|
|
853
|
+
CHALLENGE_ISSUE_FAILED: defineError("CHALLENGE_ISSUE_FAILED", "Kh\xF4ng th\u1EC3 ph\xE1t h\xE0nh challenge"),
|
|
854
|
+
/**
|
|
855
|
+
* Challenge update failed
|
|
856
|
+
*/
|
|
857
|
+
CHALLENGE_UPDATE_FAILED: defineError("CHALLENGE_UPDATE_FAILED", "Kh\xF4ng th\u1EC3 c\u1EADp nh\u1EADt challenge"),
|
|
858
|
+
/**
|
|
859
|
+
* Auth scope mismatch - route scope doesn't match challenge scope
|
|
860
|
+
*/
|
|
861
|
+
AUTH_SCOPE_MISMATCH: defineError("AUTH_SCOPE_MISMATCH", "Route auth scope does not match challenge scope"),
|
|
862
|
+
/**
|
|
863
|
+
* Too many code (re-)issues on this challenge — prevents SMS/email send spam.
|
|
864
|
+
*/
|
|
865
|
+
TOO_MANY_ISSUES: defineError("TOO_MANY_ISSUES", "Qu\xE1 nhi\u1EC1u l\u1EA7n g\u1EEDi m\xE3, vui l\xF2ng \u0111\u0103ng nh\u1EADp l\u1EA1i")
|
|
866
|
+
};
|
|
867
|
+
|
|
868
|
+
// packages/auth-core/dist/features/authentication/register/errors.js
|
|
869
|
+
var registerErrors = {
|
|
870
|
+
/**
|
|
871
|
+
* Identity plugin not found for the specified type
|
|
872
|
+
*/
|
|
873
|
+
IDENTITY_PLUGIN_NOT_FOUND: defineErrorAdvanced("IDENTITY_PLUGIN_NOT_FOUND", 'Identity plugin "{identityType}" not found'),
|
|
874
|
+
/**
|
|
875
|
+
* Credential plugin not found for the specified type
|
|
876
|
+
*/
|
|
877
|
+
CREDENTIAL_PLUGIN_NOT_FOUND: defineErrorAdvanced("CREDENTIAL_PLUGIN_NOT_FOUND", 'Credential plugin "{credentialType}" not found'),
|
|
878
|
+
/**
|
|
879
|
+
* Invalid identity format
|
|
880
|
+
*/
|
|
881
|
+
INVALID_IDENTITY_FORMAT: defineErrorAdvanced("INVALID_IDENTITY_FORMAT", "Invalid {identityType} format"),
|
|
882
|
+
/**
|
|
883
|
+
* Identity already exists (email, phone, username, wallet)
|
|
884
|
+
*/
|
|
885
|
+
IDENTITY_ALREADY_EXISTS: defineErrorAdvanced("IDENTITY_ALREADY_EXISTS", "{identityType} already exists in the system"),
|
|
886
|
+
/**
|
|
887
|
+
* Invalid credential (weak password, invalid format, etc.)
|
|
888
|
+
*/
|
|
889
|
+
INVALID_CREDENTIAL: defineError("INVALID_CREDENTIAL", "Invalid credential format or strength"),
|
|
890
|
+
/**
|
|
891
|
+
* User creation failed (database error, transaction failed, etc.)
|
|
892
|
+
*/
|
|
893
|
+
USER_CREATION_FAILED: defineError("USER_CREATION_FAILED", "Failed to create user account"),
|
|
894
|
+
EMAIL_SYSTEM_NOT_AVAILABLE: defineError("EMAIL_SYSTEM_NOT_AVAILABLE", "Email system is not available"),
|
|
895
|
+
VERIFICATION_EMAIL_SEND_FAILED: defineError("VERIFICATION_EMAIL_SEND_FAILED", "Failed to send verification email"),
|
|
896
|
+
/**
|
|
897
|
+
* Database error during registration
|
|
898
|
+
*/
|
|
899
|
+
DATABASE_ERROR: defineError("DATABASE_ERROR", "Database error occurred during registration"),
|
|
900
|
+
/**
|
|
901
|
+
* Internal error during registration
|
|
902
|
+
*/
|
|
903
|
+
INTERNAL_ERROR: defineError("INTERNAL_ERROR", "Internal error occurred during registration")
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
// packages/auth-core/dist/features/authentication/select-tenant/errors.js
|
|
907
|
+
var selectTenantErrors = {
|
|
908
|
+
/**
|
|
909
|
+
* Session not found
|
|
910
|
+
*/
|
|
911
|
+
SESSION_NOT_FOUND: defineError("SESSION_NOT_FOUND", "Session not found"),
|
|
912
|
+
/**
|
|
913
|
+
* Session has been revoked
|
|
914
|
+
*/
|
|
915
|
+
SESSION_REVOKED: defineError("SESSION_REVOKED", "Session has been revoked"),
|
|
916
|
+
/**
|
|
917
|
+
* User not found
|
|
918
|
+
*/
|
|
919
|
+
USER_NOT_FOUND: defineError("USER_NOT_FOUND", "User not found"),
|
|
920
|
+
/**
|
|
921
|
+
* The system tenant is reached only by a system login (X-Auth-Context: system),
|
|
922
|
+
* never by switching an existing session: a stolen customer/tenant token must
|
|
923
|
+
* not be enough to mint a system one.
|
|
924
|
+
*/
|
|
925
|
+
SYSTEM_TENANT_NOT_SELECTABLE: defineError("SYSTEM_TENANT_NOT_SELECTABLE", "The system tenant cannot be selected; sign in to the system scope instead")
|
|
926
|
+
};
|
|
927
|
+
|
|
928
|
+
// packages/auth-core/dist/features/authentication/step-up/errors.js
|
|
929
|
+
var stepUpErrors = {
|
|
930
|
+
STEP_UP_REQUIRED: defineError("STEP_UP_REQUIRED", "Confirm it is you before making this change"),
|
|
931
|
+
STEP_UP_UNAVAILABLE: defineError("STEP_UP_UNAVAILABLE", "This account has no way to confirm it is you (no authenticator, password or verified email)"),
|
|
932
|
+
INVALID_STEP_UP_CHALLENGE: defineError("INVALID_STEP_UP_CHALLENGE", "This confirmation is invalid or has expired"),
|
|
933
|
+
INVALID_STEP_UP_CODE: defineError("INVALID_STEP_UP_CODE", "The code or password is incorrect"),
|
|
934
|
+
STEP_UP_ATTEMPTS_EXCEEDED: defineError("STEP_UP_ATTEMPTS_EXCEEDED", "Too many attempts; start again"),
|
|
935
|
+
STEP_UP_SEND_FAILED: defineError("STEP_UP_SEND_FAILED", "Could not send the confirmation code; try again")
|
|
936
|
+
};
|
|
937
|
+
|
|
938
|
+
// packages/auth-core/dist/features/oauth-providers/get-user-providers/errors.js
|
|
939
|
+
var getUserProvidersErrors = {
|
|
940
|
+
USER_NOT_FOUND: defineError("USER_NOT_FOUND", "User not found")
|
|
941
|
+
};
|
|
942
|
+
|
|
943
|
+
// packages/auth-core/dist/features/oauth-providers/handle-oauth-callback/errors.js
|
|
944
|
+
var handleOAuthCallbackErrors = {
|
|
945
|
+
PROVIDER_NOT_FOUND: defineError("PROVIDER_NOT_FOUND", "OAuth provider not found. Make sure the provider plugin is registered."),
|
|
946
|
+
INVALID_PROVIDER_NAME: defineError("INVALID_PROVIDER_NAME", "Invalid provider name"),
|
|
947
|
+
MISSING_CODE_OR_TOKEN: defineError("MISSING_CODE_OR_TOKEN", "Either authorization code or access token is required"),
|
|
948
|
+
CODE_EXCHANGE_FAILED: defineError("CODE_EXCHANGE_FAILED", "Failed to exchange authorization code for access token"),
|
|
949
|
+
INVALID_ACCESS_TOKEN: defineError("INVALID_ACCESS_TOKEN", "Invalid or expired access token"),
|
|
950
|
+
PROFILE_FETCH_FAILED: defineError("PROFILE_FETCH_FAILED", "Failed to fetch user profile from OAuth provider"),
|
|
951
|
+
EMAIL_REQUIRED: defineError("EMAIL_REQUIRED", "Email is required from OAuth provider"),
|
|
952
|
+
ACCOUNT_LOCKED: defineError("ACCOUNT_LOCKED", "Account is locked"),
|
|
953
|
+
SESSION_CREATE_FAILED: defineError("SESSION_CREATE_FAILED", "Failed to create session"),
|
|
954
|
+
/**
|
|
955
|
+
* The provider returned an email that matches an existing account, but the
|
|
956
|
+
* provider has NOT verified ownership of that email. Auto-linking here would
|
|
957
|
+
* allow account takeover, so the user must sign in and link the provider
|
|
958
|
+
* manually instead.
|
|
959
|
+
*/
|
|
960
|
+
EMAIL_NOT_VERIFIED_BY_PROVIDER: defineError("EMAIL_NOT_VERIFIED_BY_PROVIDER", "This email is not verified by the provider; sign in and link this provider from your account settings")
|
|
961
|
+
};
|
|
962
|
+
|
|
963
|
+
// packages/auth-core/dist/features/oauth-providers/link-oauth-provider/errors.js
|
|
964
|
+
var linkOAuthProviderErrors = {
|
|
965
|
+
PROVIDER_NOT_FOUND: defineError("PROVIDER_NOT_FOUND", "OAuth provider not found"),
|
|
966
|
+
USER_NOT_FOUND: defineError("USER_NOT_FOUND", "User not found"),
|
|
967
|
+
MISSING_CODE_OR_TOKEN: defineError("MISSING_CODE_OR_TOKEN", "Either authorization code or access token is required"),
|
|
968
|
+
CODE_EXCHANGE_FAILED: defineError("CODE_EXCHANGE_FAILED", "Failed to exchange authorization code for access token"),
|
|
969
|
+
INVALID_ACCESS_TOKEN: defineError("INVALID_ACCESS_TOKEN", "Invalid or expired access token"),
|
|
970
|
+
PROFILE_FETCH_FAILED: defineError("PROFILE_FETCH_FAILED", "Failed to fetch user profile from OAuth provider"),
|
|
971
|
+
PROVIDER_ALREADY_LINKED: defineError("PROVIDER_ALREADY_LINKED", "This provider is already linked to your account"),
|
|
972
|
+
PROVIDER_LINKED_TO_ANOTHER_USER: defineError("PROVIDER_LINKED_TO_ANOTHER_USER", "This provider is already linked to another user account")
|
|
973
|
+
};
|
|
974
|
+
|
|
975
|
+
// packages/auth-core/dist/features/oauth-providers/unlink-oauth-provider/errors.js
|
|
976
|
+
var unlinkOAuthProviderErrors = {
|
|
977
|
+
USER_NOT_FOUND: defineError("USER_NOT_FOUND", "User not found"),
|
|
978
|
+
PROVIDER_NOT_LINKED: defineError("PROVIDER_NOT_LINKED", "This provider is not linked to your account"),
|
|
979
|
+
CANNOT_UNLINK_LAST_PROVIDER: defineError("CANNOT_UNLINK_LAST_PROVIDER", "Cannot unlink the last authentication method. Please add another method first.")
|
|
980
|
+
};
|
|
981
|
+
|
|
982
|
+
// packages/auth-core/dist/features/session-management/delete-session/errors.js
|
|
983
|
+
var deleteSessionErrors = {
|
|
984
|
+
SESSION_NOT_FOUND: defineError("SESSION_NOT_FOUND", "Session not found"),
|
|
985
|
+
FORBIDDEN: defineError("FORBIDDEN", "You are not authorized to delete this session"),
|
|
986
|
+
DATABASE_ERROR: defineError("DATABASE_ERROR", "Failed to delete session")
|
|
987
|
+
};
|
|
988
|
+
|
|
989
|
+
// packages/auth-core/dist/features/session-management/list-sessions/errors.js
|
|
990
|
+
var listSessionsErrors = {
|
|
991
|
+
DATABASE_ERROR: defineError("DATABASE_ERROR", "Failed to retrieve sessions")
|
|
992
|
+
};
|
|
993
|
+
|
|
994
|
+
// packages/auth-core/dist/features/session-management/revoke-token/errors.js
|
|
995
|
+
var revokeTokenErrors = {
|
|
996
|
+
INVALID_TOKEN: defineError("INVALID_TOKEN", "Invalid or expired token"),
|
|
997
|
+
SESSION_NOT_FOUND: defineError("SESSION_NOT_FOUND", "Session not found"),
|
|
998
|
+
DATABASE_ERROR: defineError("DATABASE_ERROR", "Failed to revoke token")
|
|
999
|
+
};
|
|
1000
|
+
|
|
1001
|
+
// packages/auth-core/dist/features/user-management/account-data/errors.js
|
|
1002
|
+
var accountDataErrors = {
|
|
1003
|
+
ACCOUNT_NOT_FOUND: defineError("ACCOUNT_NOT_FOUND", "Account not found")
|
|
1004
|
+
};
|
|
1005
|
+
|
|
1006
|
+
// packages/auth-core/dist/features/account-management/errors.js
|
|
1007
|
+
var accountManagementErrors = {
|
|
1008
|
+
CANNOT_REMOVE_TENANT_OWNER: defineError("CANNOT_REMOVE_TENANT_OWNER", "This account owns a tenant; transfer or close the tenant before removing the account"),
|
|
1009
|
+
CANNOT_REMOVE_ACTIVE_ACCOUNT: defineError("CANNOT_REMOVE_ACTIVE_ACCOUNT", "Cannot remove an active account. Suspend or delete the account first."),
|
|
1010
|
+
CANNOT_MODIFY_OWNER: defineError("CANNOT_MODIFY_OWNER", "Cannot modify a system tenant owner. Only another owner can perform this action."),
|
|
1011
|
+
INVALID_STATUS: defineError("INVALID_STATUS", "Invalid account status. Must be active, suspended, or deleted."),
|
|
1012
|
+
NO_CHANGES: defineError("NO_CHANGES", "At least one field must be provided")
|
|
1013
|
+
};
|
|
1014
|
+
|
|
1015
|
+
// packages/auth-core/dist/features/user-management/canonicalize-identities/errors.js
|
|
1016
|
+
var canonicalizeIdentitiesErrors = {
|
|
1017
|
+
REPOSITORY_UNSUPPORTED: defineError("CANONICALIZE_REPOSITORY_UNSUPPORTED", "The identity repository does not implement listByType and rekey"),
|
|
1018
|
+
PLUGIN_NOT_CANONICALIZING: defineError("CANONICALIZE_PLUGIN_NOT_CANONICALIZING", "The identity plugin has no canonicalize() \u2014 enable canonicalization before running the backfill")
|
|
1019
|
+
};
|
|
1020
|
+
|
|
1021
|
+
// packages/auth-core/dist/features/user-management/get-user-contact/errors.js
|
|
1022
|
+
var getUserContactErrors = {
|
|
1023
|
+
/** Missing or not active: an account that is gone or suspended shows nobody its contact details. */
|
|
1024
|
+
USER_NOT_FOUND: defineError("USER_NOT_FOUND", "User not found")
|
|
1025
|
+
};
|
|
1026
|
+
|
|
1027
|
+
// packages/auth-core/dist/features/user-management/lookup-user-by-identity/errors.js
|
|
1028
|
+
var lookupUserByIdentityErrors = {
|
|
1029
|
+
/** No usable match: missing, unverified, login-disabled, or inactive account — deliberately not told apart. */
|
|
1030
|
+
USER_NOT_FOUND: defineError("USER_NOT_FOUND", "User not found"),
|
|
1031
|
+
/** The value's lookup keys belong to more than one user (pre-backfill duplicates). */
|
|
1032
|
+
IDENTITY_AMBIGUOUS: defineError("IDENTITY_AMBIGUOUS", "Identity matches more than one user"),
|
|
1033
|
+
IDENTITY_TYPE_NOT_SUPPORTED: defineError("IDENTITY_TYPE_NOT_SUPPORTED", "Lookup is not supported for this identity type")
|
|
1034
|
+
};
|
|
1035
|
+
|
|
1036
|
+
// packages/auth-core/dist/features/user-management/lookup-user-by-identity/usecase.js
|
|
1037
|
+
var SUPPORTED_TYPES = [IDENTITY_TYPE.EMAIL, IDENTITY_TYPE.PHONE];
|
|
1038
|
+
|
|
1039
|
+
// packages/auth-core/dist/features/user-management/password-management/errors.js
|
|
1040
|
+
var passwordManagementErrors = {
|
|
1041
|
+
// ========================================
|
|
1042
|
+
// Plugin Errors
|
|
1043
|
+
// ========================================
|
|
1044
|
+
PASSWORD_PLUGIN_NOT_CONFIGURED: defineError("PASSWORD_PLUGIN_NOT_CONFIGURED", "Password credential plugin is not configured"),
|
|
1045
|
+
// ========================================
|
|
1046
|
+
// Credential Errors
|
|
1047
|
+
// ========================================
|
|
1048
|
+
PASSWORD_CREDENTIAL_NOT_FOUND: defineError("PASSWORD_CREDENTIAL_NOT_FOUND", "Password credential not found. User may not have password authentication set up."),
|
|
1049
|
+
PASSWORD_ALREADY_SET: defineError("PASSWORD_ALREADY_SET", "This account already has a password"),
|
|
1050
|
+
// ========================================
|
|
1051
|
+
// Validation Errors
|
|
1052
|
+
// ========================================
|
|
1053
|
+
INVALID_CURRENT_PASSWORD: defineError("INVALID_CURRENT_PASSWORD", "Current password is incorrect"),
|
|
1054
|
+
SAME_PASSWORD: defineError("SAME_PASSWORD", "New password cannot be the same as current password"),
|
|
1055
|
+
// ========================================
|
|
1056
|
+
// Challenge Errors
|
|
1057
|
+
// ========================================
|
|
1058
|
+
CHALLENGE_NOT_FOUND: defineError("CHALLENGE_NOT_FOUND", "Password reset challenge not found"),
|
|
1059
|
+
CHALLENGE_EXPIRED: defineError("CHALLENGE_EXPIRED", "Password reset challenge has expired"),
|
|
1060
|
+
CHALLENGE_ALREADY_USED: defineError("CHALLENGE_ALREADY_USED", "Password reset challenge has already been used"),
|
|
1061
|
+
// ========================================
|
|
1062
|
+
// Code Verification Errors
|
|
1063
|
+
// ========================================
|
|
1064
|
+
INVALID_CODE: defineError("INVALID_CODE", "Invalid reset code"),
|
|
1065
|
+
TOO_MANY_ATTEMPTS: defineError("TOO_MANY_ATTEMPTS", "Too many failed attempts. Please request a new reset code"),
|
|
1066
|
+
// ========================================
|
|
1067
|
+
// Email Errors
|
|
1068
|
+
// ========================================
|
|
1069
|
+
EMAIL_SYSTEM_NOT_AVAILABLE: defineError("EMAIL_SYSTEM_NOT_AVAILABLE", "Email system is not configured"),
|
|
1070
|
+
SEND_EMAIL_ERROR: defineError("SEND_EMAIL_ERROR", "Failed to send password reset email"),
|
|
1071
|
+
// ========================================
|
|
1072
|
+
// Auth Scope Errors
|
|
1073
|
+
// ========================================
|
|
1074
|
+
AUTH_SCOPE_MISMATCH: defineError("AUTH_SCOPE_MISMATCH", "Route auth scope does not match challenge scope")
|
|
1075
|
+
};
|
|
1076
|
+
var changePasswordErrors = {
|
|
1077
|
+
PASSWORD_PLUGIN_NOT_CONFIGURED: passwordManagementErrors.PASSWORD_PLUGIN_NOT_CONFIGURED,
|
|
1078
|
+
PASSWORD_CREDENTIAL_NOT_FOUND: passwordManagementErrors.PASSWORD_CREDENTIAL_NOT_FOUND,
|
|
1079
|
+
INVALID_CURRENT_PASSWORD: passwordManagementErrors.INVALID_CURRENT_PASSWORD,
|
|
1080
|
+
SAME_PASSWORD: passwordManagementErrors.SAME_PASSWORD
|
|
1081
|
+
};
|
|
1082
|
+
var setPasswordErrors = {
|
|
1083
|
+
PASSWORD_PLUGIN_NOT_CONFIGURED: passwordManagementErrors.PASSWORD_PLUGIN_NOT_CONFIGURED,
|
|
1084
|
+
PASSWORD_ALREADY_SET: passwordManagementErrors.PASSWORD_ALREADY_SET
|
|
1085
|
+
};
|
|
1086
|
+
var forgotPasswordErrors = {
|
|
1087
|
+
EMAIL_SYSTEM_NOT_AVAILABLE: passwordManagementErrors.EMAIL_SYSTEM_NOT_AVAILABLE,
|
|
1088
|
+
SEND_EMAIL_ERROR: passwordManagementErrors.SEND_EMAIL_ERROR
|
|
1089
|
+
};
|
|
1090
|
+
var resetPasswordErrors = {
|
|
1091
|
+
PASSWORD_PLUGIN_NOT_CONFIGURED: passwordManagementErrors.PASSWORD_PLUGIN_NOT_CONFIGURED,
|
|
1092
|
+
CHALLENGE_NOT_FOUND: passwordManagementErrors.CHALLENGE_NOT_FOUND,
|
|
1093
|
+
CHALLENGE_EXPIRED: passwordManagementErrors.CHALLENGE_EXPIRED,
|
|
1094
|
+
CHALLENGE_ALREADY_USED: passwordManagementErrors.CHALLENGE_ALREADY_USED,
|
|
1095
|
+
INVALID_CODE: passwordManagementErrors.INVALID_CODE,
|
|
1096
|
+
TOO_MANY_ATTEMPTS: passwordManagementErrors.TOO_MANY_ATTEMPTS,
|
|
1097
|
+
AUTH_SCOPE_MISMATCH: passwordManagementErrors.AUTH_SCOPE_MISMATCH
|
|
1098
|
+
};
|
|
1099
|
+
|
|
1100
|
+
// packages/auth-core/dist/features/user-management/update-profile/errors.js
|
|
1101
|
+
var updateUserProfileErrors = {
|
|
1102
|
+
NO_CHANGES_PROVIDED: defineError("NO_CHANGES_PROVIDED", "At least one field must be provided to update the profile")
|
|
1103
|
+
};
|
|
1104
|
+
|
|
1105
|
+
// packages/auth-core/dist/plugin-system/default-descriptors.js
|
|
1106
|
+
var corePluginDescriptors = [
|
|
1107
|
+
// REMOVED: id plugin - ID generation is now handled by repositories
|
|
1108
|
+
// REMOVED SCHEMA_V4: verificationCode - replaced by Challenge-based verification
|
|
1109
|
+
// REMOVED: password plugin - now part of credential registry (plugin-first architecture)
|
|
1110
|
+
// REMOVED: validator plugin - validation is handled at adapter/entry-point layer
|
|
1111
|
+
{
|
|
1112
|
+
name: "token",
|
|
1113
|
+
required: true,
|
|
1114
|
+
dependencies: []
|
|
1115
|
+
// Token JTI is now generated by SessionRepository
|
|
1116
|
+
},
|
|
1117
|
+
{
|
|
1118
|
+
name: "database",
|
|
1119
|
+
required: true,
|
|
1120
|
+
dependencies: []
|
|
1121
|
+
},
|
|
1122
|
+
{
|
|
1123
|
+
name: "emailSystem",
|
|
1124
|
+
required: true,
|
|
1125
|
+
dependencies: []
|
|
1126
|
+
// Email system can depend on transport/renderer if needed
|
|
1127
|
+
}
|
|
1128
|
+
];
|
|
1129
|
+
var optionalPluginDescriptors = [
|
|
1130
|
+
{
|
|
1131
|
+
name: "emailTransport",
|
|
1132
|
+
required: false,
|
|
1133
|
+
dependencies: []
|
|
1134
|
+
},
|
|
1135
|
+
{
|
|
1136
|
+
name: "emailTemplateRepository",
|
|
1137
|
+
required: false,
|
|
1138
|
+
dependencies: []
|
|
1139
|
+
},
|
|
1140
|
+
{
|
|
1141
|
+
name: "emailTemplateRenderer",
|
|
1142
|
+
required: false,
|
|
1143
|
+
dependencies: []
|
|
1144
|
+
},
|
|
1145
|
+
{
|
|
1146
|
+
name: "deviceParser",
|
|
1147
|
+
required: false,
|
|
1148
|
+
dependencies: []
|
|
1149
|
+
},
|
|
1150
|
+
{
|
|
1151
|
+
name: "audit",
|
|
1152
|
+
required: false,
|
|
1153
|
+
dependencies: ["deviceParser"]
|
|
1154
|
+
// Audit may need device parser (IDs come from repositories)
|
|
1155
|
+
},
|
|
1156
|
+
{
|
|
1157
|
+
name: "mfa",
|
|
1158
|
+
required: false,
|
|
1159
|
+
dependencies: ["token"]
|
|
1160
|
+
// MFA needs token (SCHEMA_V4: verification now uses Challenge)
|
|
1161
|
+
},
|
|
1162
|
+
// Single-instance optional plugins with no dependencies. Every optional plugin MUST
|
|
1163
|
+
// have a descriptor: the builder only initializes descriptor-listed names, so an
|
|
1164
|
+
// override without one is silently dropped (this is how rateLimiter went missing).
|
|
1165
|
+
{
|
|
1166
|
+
name: "smsSystem",
|
|
1167
|
+
required: false,
|
|
1168
|
+
dependencies: []
|
|
1169
|
+
},
|
|
1170
|
+
{
|
|
1171
|
+
name: "rateLimiter",
|
|
1172
|
+
required: false,
|
|
1173
|
+
dependencies: []
|
|
1174
|
+
},
|
|
1175
|
+
{
|
|
1176
|
+
name: "revocation",
|
|
1177
|
+
required: false,
|
|
1178
|
+
dependencies: []
|
|
1179
|
+
},
|
|
1180
|
+
{
|
|
1181
|
+
name: "appAccess",
|
|
1182
|
+
required: false,
|
|
1183
|
+
dependencies: []
|
|
1184
|
+
}
|
|
1185
|
+
// Note: OAuth providers are now dynamically registered via oauthProviders Map
|
|
1186
|
+
// See PluginRegistry.oauthProviders instead of individual provider plugins
|
|
1187
|
+
];
|
|
1188
|
+
var allPluginDescriptors = [...corePluginDescriptors, ...optionalPluginDescriptors];
|
|
1189
|
+
|
|
1190
|
+
// packages/auth-core/dist/utils/debug-logger.js
|
|
1191
|
+
var LOG_LEVELS = {
|
|
1192
|
+
debug: 0,
|
|
1193
|
+
info: 1,
|
|
1194
|
+
warn: 2,
|
|
1195
|
+
error: 3
|
|
1196
|
+
};
|
|
1197
|
+
var DebugLogger = class {
|
|
1198
|
+
enabled;
|
|
1199
|
+
prefix;
|
|
1200
|
+
minLevel;
|
|
1201
|
+
constructor(config) {
|
|
1202
|
+
this.enabled = config.enabled;
|
|
1203
|
+
this.prefix = config.prefix ?? "[auth-core]";
|
|
1204
|
+
this.minLevel = LOG_LEVELS[config.minLevel ?? "debug"];
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Check if logging is enabled for a level
|
|
1208
|
+
*/
|
|
1209
|
+
shouldLog(level) {
|
|
1210
|
+
return this.enabled && LOG_LEVELS[level] >= this.minLevel;
|
|
1211
|
+
}
|
|
1212
|
+
/**
|
|
1213
|
+
* Format log message with timestamp
|
|
1214
|
+
*/
|
|
1215
|
+
format(level, message, ..._args) {
|
|
1216
|
+
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
1217
|
+
const levelStr = level.toUpperCase().padEnd(5);
|
|
1218
|
+
return `${this.prefix} [${timestamp}] ${levelStr} ${message}`;
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Debug level log
|
|
1222
|
+
*/
|
|
1223
|
+
debug(message, ...args) {
|
|
1224
|
+
if (this.shouldLog("debug")) {
|
|
1225
|
+
console.debug(this.format("debug", message), ...args);
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
/**
|
|
1229
|
+
* Info level log
|
|
1230
|
+
*/
|
|
1231
|
+
info(message, ...args) {
|
|
1232
|
+
if (this.shouldLog("info")) {
|
|
1233
|
+
console.info(this.format("info", message), ...args);
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* Warn level log
|
|
1238
|
+
*/
|
|
1239
|
+
warn(message, ...args) {
|
|
1240
|
+
if (this.shouldLog("warn")) {
|
|
1241
|
+
console.warn(this.format("warn", message), ...args);
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
/**
|
|
1245
|
+
* Error level log
|
|
1246
|
+
*/
|
|
1247
|
+
error(message, ...args) {
|
|
1248
|
+
if (this.shouldLog("error")) {
|
|
1249
|
+
console.error(this.format("error", message), ...args);
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
/**
|
|
1253
|
+
* Log with timing information
|
|
1254
|
+
*/
|
|
1255
|
+
time(label) {
|
|
1256
|
+
if (this.enabled) {
|
|
1257
|
+
console.time(`${this.prefix} ${label}`);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* End timing log
|
|
1262
|
+
*/
|
|
1263
|
+
timeEnd(label) {
|
|
1264
|
+
if (this.enabled) {
|
|
1265
|
+
console.timeEnd(`${this.prefix} ${label}`);
|
|
1266
|
+
}
|
|
1267
|
+
}
|
|
1268
|
+
/**
|
|
1269
|
+
* Group logs
|
|
1270
|
+
*/
|
|
1271
|
+
group(label) {
|
|
1272
|
+
if (this.enabled) {
|
|
1273
|
+
console.group(`${this.prefix} ${label}`);
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
/**
|
|
1277
|
+
* End log group
|
|
1278
|
+
*/
|
|
1279
|
+
groupEnd() {
|
|
1280
|
+
if (this.enabled) {
|
|
1281
|
+
console.groupEnd();
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
};
|
|
1285
|
+
var nullLogger = new DebugLogger({ enabled: false });
|
|
1286
|
+
|
|
1287
|
+
// packages/email-delivery/dist/inbound.js
|
|
1288
|
+
var inboundErrors = {
|
|
1289
|
+
INVALID_ROUTES: defineErrorAdvanced("EMAIL_INBOUND_ROUTES_INVALID", "EMAIL_INBOUND_ROUTES: {problem}")
|
|
1290
|
+
};
|
|
1291
|
+
var ADDRESS = /^[^\s@<>,;]+@[^\s@<>,;]+\.[^\s@<>,;]+$/;
|
|
1292
|
+
var KEY = /^(\*|\*@[^\s@<>,;]+|[^\s@<>,;*]+@[^\s@<>,;]+)$/;
|
|
1293
|
+
function parseInboundRoutes(json) {
|
|
1294
|
+
let raw;
|
|
1295
|
+
try {
|
|
1296
|
+
raw = JSON.parse(json);
|
|
1297
|
+
} catch {
|
|
1298
|
+
return err(inboundErrors.INVALID_ROUTES({ problem: "must be JSON" }));
|
|
1299
|
+
}
|
|
1300
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
1301
|
+
return err(inboundErrors.INVALID_ROUTES({ problem: "must be an object of address \u2192 rule" }));
|
|
1302
|
+
}
|
|
1303
|
+
const routes = /* @__PURE__ */ new Map();
|
|
1304
|
+
for (const [rawKey, rule] of Object.entries(raw)) {
|
|
1305
|
+
const key = rawKey.trim().toLowerCase();
|
|
1306
|
+
if (!KEY.test(key))
|
|
1307
|
+
return err(inboundErrors.INVALID_ROUTES({ problem: `bad key ${JSON.stringify(rawKey)}` }));
|
|
1308
|
+
const r = typeof rule === "object" && rule !== null ? rule : {};
|
|
1309
|
+
if (r.action === "forward") {
|
|
1310
|
+
const to = r.to;
|
|
1311
|
+
if (!Array.isArray(to) || to.length === 0 || to.length > 10) {
|
|
1312
|
+
return err(inboundErrors.INVALID_ROUTES({ problem: `${key}: forward needs 1-10 addresses in "to"` }));
|
|
1313
|
+
}
|
|
1314
|
+
if (!to.every((a) => typeof a === "string" && ADDRESS.test(a))) {
|
|
1315
|
+
return err(inboundErrors.INVALID_ROUTES({ problem: `${key}: forward "to" must be email addresses` }));
|
|
1316
|
+
}
|
|
1317
|
+
routes.set(key, { action: "forward", to });
|
|
1318
|
+
} else if (r.action === "reject") {
|
|
1319
|
+
if (r.reason !== void 0 && (typeof r.reason !== "string" || /[\r\n]/.test(r.reason) || r.reason.length > 200)) {
|
|
1320
|
+
return err(inboundErrors.INVALID_ROUTES({ problem: `${key}: reason must be one line, \u2264 200 chars` }));
|
|
1321
|
+
}
|
|
1322
|
+
routes.set(key, typeof r.reason === "string" ? { action: "reject", reason: r.reason } : { action: "reject" });
|
|
1323
|
+
} else if (r.action === "drop") {
|
|
1324
|
+
routes.set(key, { action: "drop" });
|
|
1325
|
+
} else {
|
|
1326
|
+
return err(inboundErrors.INVALID_ROUTES({ problem: `${key}: action must be forward | reject | drop` }));
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
return ok(routes);
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
// packages/mfa-plugin-totp/dist/bip39-english.js
|
|
1333
|
+
var BIP39_ENGLISH = "abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo".split(" ");
|
|
1334
|
+
|
|
1335
|
+
// packages/mfa-plugin-totp/dist/recovery-phrase.js
|
|
1336
|
+
var BY_PREFIX = new Map(BIP39_ENGLISH.map((word) => [word.slice(0, 4), word]));
|
|
1337
|
+
var WORDS = new Set(BIP39_ENGLISH);
|
|
1338
|
+
|
|
1339
|
+
// packages/mfa-plugin-totp/dist/secret-cipher.js
|
|
1340
|
+
var PREFIX = "enc:v1:";
|
|
1341
|
+
var AAD = new TextEncoder().encode("auth-craft:totp-secret:v1");
|
|
1342
|
+
var KEY_ID = /^[A-Za-z0-9_-]{1,32}$/;
|
|
1343
|
+
var totpSecretErrors = {
|
|
1344
|
+
KEY_UNKNOWN: {
|
|
1345
|
+
code: "TOTP_SECRET_KEY_UNKNOWN",
|
|
1346
|
+
message: "The TOTP secret was encrypted with a key that is not configured"
|
|
1347
|
+
},
|
|
1348
|
+
KEY_MISSING: {
|
|
1349
|
+
code: "TOTP_SECRET_KEY_MISSING",
|
|
1350
|
+
message: "The TOTP secret is encrypted but no decryption keys are configured"
|
|
1351
|
+
},
|
|
1352
|
+
DECRYPT_FAILED: { code: "TOTP_SECRET_DECRYPT_FAILED", message: "The TOTP secret could not be decrypted" }
|
|
1353
|
+
};
|
|
1354
|
+
var isEncryptedTotpSecret = (stored) => stored.startsWith(PREFIX);
|
|
1355
|
+
function toBase64Url(bytes) {
|
|
1356
|
+
let binary = "";
|
|
1357
|
+
for (const b of bytes)
|
|
1358
|
+
binary += String.fromCharCode(b);
|
|
1359
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1360
|
+
}
|
|
1361
|
+
function fromBase64Url(value) {
|
|
1362
|
+
const base64 = value.replace(/-/g, "+").replace(/_/g, "/");
|
|
1363
|
+
const binary = atob(base64 + "=".repeat((4 - base64.length % 4) % 4));
|
|
1364
|
+
return Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
1365
|
+
}
|
|
1366
|
+
function createTotpSecretCipher(config) {
|
|
1367
|
+
if (!(config.activeKeyId in config.keys))
|
|
1368
|
+
throw new Error("TOTP secret keys: activeKeyId is not in keys");
|
|
1369
|
+
const raw = /* @__PURE__ */ new Map();
|
|
1370
|
+
for (const [id, hex] of Object.entries(config.keys)) {
|
|
1371
|
+
if (!KEY_ID.test(id))
|
|
1372
|
+
throw new Error(`TOTP secret keys: invalid key id '${id}' (A-Z a-z 0-9 _ -, \u2264 32)`);
|
|
1373
|
+
if (!/^[0-9a-fA-F]{64}$/.test(hex))
|
|
1374
|
+
throw new Error(`TOTP secret keys: key '${id}' must be 64 hex characters`);
|
|
1375
|
+
raw.set(id, Uint8Array.from(hex.match(/../g) ?? [], (h) => Number.parseInt(h, 16)));
|
|
1376
|
+
}
|
|
1377
|
+
const imported = /* @__PURE__ */ new Map();
|
|
1378
|
+
const keyFor = (id) => {
|
|
1379
|
+
const bytes = raw.get(id);
|
|
1380
|
+
if (!bytes)
|
|
1381
|
+
return void 0;
|
|
1382
|
+
let key = imported.get(id);
|
|
1383
|
+
if (!key) {
|
|
1384
|
+
key = crypto.subtle.importKey("raw", bytes, "AES-GCM", false, ["encrypt", "decrypt"]);
|
|
1385
|
+
imported.set(id, key);
|
|
1386
|
+
}
|
|
1387
|
+
return key;
|
|
1388
|
+
};
|
|
1389
|
+
return {
|
|
1390
|
+
async encrypt(secret) {
|
|
1391
|
+
const key = await keyFor(config.activeKeyId);
|
|
1392
|
+
if (!key)
|
|
1393
|
+
throw new Error("unreachable: active key checked at construction");
|
|
1394
|
+
const iv = crypto.getRandomValues(new Uint8Array(12));
|
|
1395
|
+
const sealed = await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: AAD }, key, new TextEncoder().encode(secret));
|
|
1396
|
+
return `${PREFIX}${config.activeKeyId}:${toBase64Url(iv)}:${toBase64Url(new Uint8Array(sealed))}`;
|
|
1397
|
+
},
|
|
1398
|
+
async decrypt(stored) {
|
|
1399
|
+
if (!isEncryptedTotpSecret(stored))
|
|
1400
|
+
return ok(stored);
|
|
1401
|
+
const [keyId, iv, sealed, ...rest] = stored.slice(PREFIX.length).split(":");
|
|
1402
|
+
if (!keyId || !iv || !sealed || rest.length > 0)
|
|
1403
|
+
return err(totpSecretErrors.DECRYPT_FAILED);
|
|
1404
|
+
const key = keyFor(keyId);
|
|
1405
|
+
if (!key)
|
|
1406
|
+
return err(totpSecretErrors.KEY_UNKNOWN);
|
|
1407
|
+
try {
|
|
1408
|
+
const plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: fromBase64Url(iv), additionalData: AAD }, await key, fromBase64Url(sealed));
|
|
1409
|
+
return ok(new TextDecoder().decode(plain));
|
|
1410
|
+
} catch {
|
|
1411
|
+
return err(totpSecretErrors.DECRYPT_FAILED);
|
|
1412
|
+
}
|
|
1413
|
+
},
|
|
1414
|
+
needsEncryption(stored) {
|
|
1415
|
+
return !stored.startsWith(`${PREFIX}${config.activeKeyId}:`);
|
|
1416
|
+
}
|
|
1417
|
+
};
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
// packages/mfa-plugin-totp/dist/encrypt-stored-secrets.js
|
|
1421
|
+
function totpSecretKeysFromEnv(env) {
|
|
1422
|
+
const active = env.MFA_SECRET_KEY?.trim();
|
|
1423
|
+
if (!active)
|
|
1424
|
+
return null;
|
|
1425
|
+
const activeKeyId = env.MFA_SECRET_KEY_ID?.trim() || "k1";
|
|
1426
|
+
const keys = {};
|
|
1427
|
+
for (const entry of (env.MFA_SECRET_PREVIOUS_KEYS ?? "").split(",").map((e) => e.trim())) {
|
|
1428
|
+
if (!entry)
|
|
1429
|
+
continue;
|
|
1430
|
+
const [id, hex, ...rest] = entry.split(":");
|
|
1431
|
+
if (!id || !hex || rest.length > 0)
|
|
1432
|
+
throw new Error('MFA_SECRET_PREVIOUS_KEYS must be "id:hex,id:hex"');
|
|
1433
|
+
keys[id] = hex;
|
|
1434
|
+
}
|
|
1435
|
+
keys[activeKeyId] = active;
|
|
1436
|
+
createTotpSecretCipher({ keys, activeKeyId });
|
|
1437
|
+
return { keys, activeKeyId };
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
// apps/auth-worker-d1/src/origin-policy.ts
|
|
1441
|
+
var LOCAL_HTTP = /^http:\/\/(localhost|127\.0\.0\.1)(:\d{1,5})?$/;
|
|
1442
|
+
var HOST_LABELS = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/;
|
|
1443
|
+
function asOrigin(value) {
|
|
1444
|
+
try {
|
|
1445
|
+
const url = new URL(value);
|
|
1446
|
+
return url.origin === value.toLowerCase() && url.origin !== "null" ? url.origin : null;
|
|
1447
|
+
} catch {
|
|
1448
|
+
return null;
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
function parseOriginPolicy(entries) {
|
|
1452
|
+
const exact = /* @__PURE__ */ new Set();
|
|
1453
|
+
const suffixes = [];
|
|
1454
|
+
const problems = [];
|
|
1455
|
+
for (const entry of entries) {
|
|
1456
|
+
if (entry === "*") {
|
|
1457
|
+
problems.push('CORS_ORIGINS: "*" is not allowed with credentials; list the origins');
|
|
1458
|
+
continue;
|
|
1459
|
+
}
|
|
1460
|
+
const pattern = entry.match(/^https:\/\/\*\.(.+)$/i);
|
|
1461
|
+
if (pattern?.[1]) {
|
|
1462
|
+
const domain = pattern[1].toLowerCase();
|
|
1463
|
+
if (!HOST_LABELS.test(domain)) problems.push(`CORS_ORIGINS: "${entry}" is not a valid pattern`);
|
|
1464
|
+
else suffixes.push(`.${domain}`);
|
|
1465
|
+
continue;
|
|
1466
|
+
}
|
|
1467
|
+
if (entry.includes("*")) {
|
|
1468
|
+
problems.push(`CORS_ORIGINS: "${entry}" is not a valid pattern (only https://*.domain)`);
|
|
1469
|
+
continue;
|
|
1470
|
+
}
|
|
1471
|
+
const origin = asOrigin(entry);
|
|
1472
|
+
if (!origin) {
|
|
1473
|
+
problems.push(`CORS_ORIGINS: "${entry}" is not an origin (scheme://host[:port], no path)`);
|
|
1474
|
+
continue;
|
|
1475
|
+
}
|
|
1476
|
+
if (!origin.startsWith("https://") && !LOCAL_HTTP.test(origin)) {
|
|
1477
|
+
problems.push(`CORS_ORIGINS: "${entry}" must be https (http only for localhost)`);
|
|
1478
|
+
continue;
|
|
1479
|
+
}
|
|
1480
|
+
exact.add(origin);
|
|
1481
|
+
}
|
|
1482
|
+
return {
|
|
1483
|
+
problems,
|
|
1484
|
+
policy: {
|
|
1485
|
+
configured: exact.size > 0 || suffixes.length > 0,
|
|
1486
|
+
allows(origin) {
|
|
1487
|
+
const canonical = asOrigin(origin);
|
|
1488
|
+
if (!canonical) return false;
|
|
1489
|
+
if (exact.has(canonical)) return true;
|
|
1490
|
+
if (!canonical.startsWith("https://")) return false;
|
|
1491
|
+
const url = new URL(canonical);
|
|
1492
|
+
if (url.port !== "") return false;
|
|
1493
|
+
return suffixes.some((suffix) => url.hostname.endsWith(suffix) && url.hostname.length > suffix.length);
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
};
|
|
1497
|
+
}
|
|
1498
|
+
|
|
1499
|
+
// apps/auth-worker-d1/src/config.ts
|
|
1500
|
+
var configErrors = {
|
|
1501
|
+
INVALID: defineErrorAdvanced("WORKER_CONFIG_INVALID", "Invalid worker configuration ({count} issues):\n{details}")
|
|
1502
|
+
};
|
|
1503
|
+
var DEFAULTS = {
|
|
1504
|
+
NODE_ENV: "production",
|
|
1505
|
+
JWT_ALGORITHM: "EdDSA",
|
|
1506
|
+
AUTH_SYSTEM_NAME: "auth-worker-d1",
|
|
1507
|
+
APP_URL: "http://localhost:8787",
|
|
1508
|
+
SUPPORT_EMAIL: "support@yourapp.com",
|
|
1509
|
+
APP_VERSION: "1.0.0",
|
|
1510
|
+
ACCESS_TOKEN_LIFETIME_MINUTES: "15",
|
|
1511
|
+
REFRESH_TOKEN_LIFETIME_MINUTES: "10080",
|
|
1512
|
+
VERIFICATION_CODE_LIFETIME_MINUTES: "10",
|
|
1513
|
+
VERIFICATION_RESEND_COOLDOWN_SECONDS: "60",
|
|
1514
|
+
REFRESH_TOKEN_GRACE_WINDOW_MS: "30000",
|
|
1515
|
+
REFRESH_TOKEN_STRATEGY: "body",
|
|
1516
|
+
REFRESH_TOKEN_COOKIE_NAME: "refresh_token",
|
|
1517
|
+
REFRESH_TOKEN_COOKIE_HTTP_ONLY: "true",
|
|
1518
|
+
REFRESH_TOKEN_COOKIE_SECURE: "true",
|
|
1519
|
+
REFRESH_TOKEN_COOKIE_SAME_SITE: "strict",
|
|
1520
|
+
REFRESH_TOKEN_COOKIE_PATH: "/",
|
|
1521
|
+
REQUIRE_VERIFIED_IDENTITY: "true",
|
|
1522
|
+
EMAIL_CANONICALIZE: "false",
|
|
1523
|
+
EMAIL_CANONICAL_LEGACY_LOOKUP: "true",
|
|
1524
|
+
MAX_LOGIN_ATTEMPTS: "5",
|
|
1525
|
+
LOCKOUT_DURATION_MINUTES: "30",
|
|
1526
|
+
VERIFY_SESSION_ON_AUTH: "false",
|
|
1527
|
+
SYSTEM_TENANT_ID: "__system__",
|
|
1528
|
+
CORS_ORIGINS_DYNAMIC: "false",
|
|
1529
|
+
CORS_ORIGINS_CACHE_SECONDS: "30",
|
|
1530
|
+
OWNERSHIP_TRANSFER_ENABLED: "true",
|
|
1531
|
+
SECURITY_NOTIFICATIONS_ENABLED: "true",
|
|
1532
|
+
SERVICE_JWT_ALGORITHM: "EdDSA",
|
|
1533
|
+
INTERNAL_JWT_ISSUER: "auth-craft",
|
|
1534
|
+
INTERNAL_JWT_AUDIENCE: "auth-craft:internal",
|
|
1535
|
+
SERVICE_ROUTE_PATH: "/internal",
|
|
1536
|
+
EMAIL_MODE: "console",
|
|
1537
|
+
EMAIL_MAX_AGE_MINUTES: "15",
|
|
1538
|
+
EMAIL_RETRY_BASE_SECONDS: "30",
|
|
1539
|
+
EMAIL_INBOUND_MAX_BYTES: "26214400",
|
|
1540
|
+
EMAIL_LOG_RETENTION_DAYS: "30",
|
|
1541
|
+
PASSWORD_ENGINE_TIMEOUT_MS: "3000",
|
|
1542
|
+
EMAIL_RELAY_TIMEOUT_MS: "5000",
|
|
1543
|
+
FACEBOOK_REDIRECT_URI: "http://localhost:8787/auth/oauth/facebook/callback",
|
|
1544
|
+
GOOGLE_REDIRECT_URI: "http://localhost:8787/auth/oauth/google/callback",
|
|
1545
|
+
AUDIT_ENABLED: "true",
|
|
1546
|
+
AUDIT_STORE: "log",
|
|
1547
|
+
AUDIT_RETENTION_DAYS: "90",
|
|
1548
|
+
DEVICE_TRACKING: "true"
|
|
1549
|
+
};
|
|
1550
|
+
var EnvReader = class {
|
|
1551
|
+
constructor(env) {
|
|
1552
|
+
this.env = env;
|
|
1553
|
+
}
|
|
1554
|
+
env;
|
|
1555
|
+
issues = [];
|
|
1556
|
+
str(name) {
|
|
1557
|
+
const value = this.env[name];
|
|
1558
|
+
if (typeof value === "string" && value !== "") return value;
|
|
1559
|
+
return DEFAULTS[name] ?? "";
|
|
1560
|
+
}
|
|
1561
|
+
/** Set by the operator (not a default). */
|
|
1562
|
+
explicit(name) {
|
|
1563
|
+
const value = this.env[name];
|
|
1564
|
+
return typeof value === "string" && value !== "";
|
|
1565
|
+
}
|
|
1566
|
+
optional(name) {
|
|
1567
|
+
const value = this.str(name);
|
|
1568
|
+
return value === "" ? void 0 : value;
|
|
1569
|
+
}
|
|
1570
|
+
required(name, when = true) {
|
|
1571
|
+
const value = this.str(name);
|
|
1572
|
+
if (when && value === "") this.issues.push(`${name}: required`);
|
|
1573
|
+
return value;
|
|
1574
|
+
}
|
|
1575
|
+
int(name, min = 0) {
|
|
1576
|
+
const value = Number(this.str(name));
|
|
1577
|
+
if (!Number.isInteger(value) || value < min) {
|
|
1578
|
+
this.issues.push(`${name}: must be an integer >= ${min}`);
|
|
1579
|
+
return min;
|
|
1580
|
+
}
|
|
1581
|
+
return value;
|
|
1582
|
+
}
|
|
1583
|
+
bool(name) {
|
|
1584
|
+
const raw = this.str(name);
|
|
1585
|
+
if (raw === "true") return true;
|
|
1586
|
+
if (raw === "false" || raw === "") return false;
|
|
1587
|
+
this.issues.push(`${name}: must be true or false`);
|
|
1588
|
+
return false;
|
|
1589
|
+
}
|
|
1590
|
+
oneOf(name, allowed) {
|
|
1591
|
+
const raw = this.str(name);
|
|
1592
|
+
if (allowed.includes(raw)) return raw;
|
|
1593
|
+
this.issues.push(`${name}: must be one of ${allowed.join(" | ")}`);
|
|
1594
|
+
return allowed[0];
|
|
1595
|
+
}
|
|
1596
|
+
list(name) {
|
|
1597
|
+
return this.str(name).split(",").map((s) => s.trim()).filter(Boolean);
|
|
1598
|
+
}
|
|
1599
|
+
};
|
|
1600
|
+
var normalizePath = (raw) => raw ? (raw.startsWith("/") ? raw : `/${raw}`).replace(/\/+$/, "") : "";
|
|
1601
|
+
var PRESET_APP_VARS = [
|
|
1602
|
+
"JWT_CUSTOMER_AUDIENCE",
|
|
1603
|
+
"JWT_TENANT_AUDIENCE",
|
|
1604
|
+
"JWT_SYSTEM_AUDIENCE",
|
|
1605
|
+
"TOKEN_AUD_CUSTOMER",
|
|
1606
|
+
"TOKEN_AUD_TENANT",
|
|
1607
|
+
"TOKEN_AUD_SYSTEM",
|
|
1608
|
+
"REFRESH_COOKIE_CUSTOMER",
|
|
1609
|
+
"REFRESH_COOKIE_TENANT",
|
|
1610
|
+
"REFRESH_COOKIE_SYSTEM",
|
|
1611
|
+
"REFRESH_TOKEN_STRATEGY_CUSTOMER",
|
|
1612
|
+
"REFRESH_TOKEN_STRATEGY_TENANT",
|
|
1613
|
+
"REFRESH_TOKEN_STRATEGY_SYSTEM"
|
|
1614
|
+
];
|
|
1615
|
+
var STRATEGIES2 = ["body", "cookie", "both"];
|
|
1616
|
+
function readRefreshTokenStrategy(r) {
|
|
1617
|
+
const global = r.oneOf("REFRESH_TOKEN_STRATEGY", STRATEGIES2);
|
|
1618
|
+
const perApp = {
|
|
1619
|
+
customer: r.optional("REFRESH_TOKEN_STRATEGY_CUSTOMER"),
|
|
1620
|
+
tenant: r.optional("REFRESH_TOKEN_STRATEGY_TENANT"),
|
|
1621
|
+
system: r.optional("REFRESH_TOKEN_STRATEGY_SYSTEM")
|
|
1622
|
+
};
|
|
1623
|
+
if (Object.values(perApp).every((v) => v === void 0)) return global;
|
|
1624
|
+
const pick = (name, value) => value === void 0 ? global : r.oneOf(name, STRATEGIES2);
|
|
1625
|
+
return {
|
|
1626
|
+
customer: pick("REFRESH_TOKEN_STRATEGY_CUSTOMER", perApp.customer),
|
|
1627
|
+
tenant: pick("REFRESH_TOKEN_STRATEGY_TENANT", perApp.tenant),
|
|
1628
|
+
system: pick("REFRESH_TOKEN_STRATEGY_SYSTEM", perApp.system)
|
|
1629
|
+
};
|
|
1630
|
+
}
|
|
1631
|
+
var usesCookie = (strategy) => (typeof strategy === "string" ? [strategy] : Object.values(strategy)).some((s) => s !== "body");
|
|
1632
|
+
function loadWorkerConfig(env) {
|
|
1633
|
+
const r = new EnvReader(env);
|
|
1634
|
+
const refreshTokenStrategy = readRefreshTokenStrategy(r);
|
|
1635
|
+
const config = {
|
|
1636
|
+
nodeEnv: r.oneOf("NODE_ENV", ["production", "staging", "development", "test"]),
|
|
1637
|
+
basePath: normalizePath(r.str("APP_BASE_PATH")),
|
|
1638
|
+
jwt: {
|
|
1639
|
+
algorithm: r.oneOf("JWT_ALGORITHM", ["EdDSA", "HS256", "HS384", "HS512"]),
|
|
1640
|
+
privateKey: r.required("JWT_PRIVATE_KEY"),
|
|
1641
|
+
publicKey: r.required("JWT_PUBLIC_KEY"),
|
|
1642
|
+
issuer: r.optional("JWT_ISSUER") ?? r.str("AUTH_SYSTEM_NAME")
|
|
1643
|
+
},
|
|
1644
|
+
auth: {
|
|
1645
|
+
systemName: r.str("AUTH_SYSTEM_NAME"),
|
|
1646
|
+
appUrl: r.str("APP_URL"),
|
|
1647
|
+
supportEmail: r.str("SUPPORT_EMAIL"),
|
|
1648
|
+
appVersion: r.str("APP_VERSION"),
|
|
1649
|
+
accessTokenLifetimeMinutes: r.int("ACCESS_TOKEN_LIFETIME_MINUTES", 1),
|
|
1650
|
+
refreshTokenLifetimeMinutes: r.int("REFRESH_TOKEN_LIFETIME_MINUTES", 1),
|
|
1651
|
+
verificationCodeLifetimeMinutes: r.int("VERIFICATION_CODE_LIFETIME_MINUTES", 1),
|
|
1652
|
+
refreshTokenStrategy
|
|
1653
|
+
},
|
|
1654
|
+
emailIdentity: {
|
|
1655
|
+
canonicalize: r.bool("EMAIL_CANONICALIZE"),
|
|
1656
|
+
legacyLookup: r.bool("EMAIL_CANONICAL_LEGACY_LOOKUP")
|
|
1657
|
+
},
|
|
1658
|
+
security: {
|
|
1659
|
+
requireVerifiedIdentity: r.bool("REQUIRE_VERIFIED_IDENTITY"),
|
|
1660
|
+
maxLoginAttempts: r.int("MAX_LOGIN_ATTEMPTS", 1),
|
|
1661
|
+
lockoutDurationMinutes: r.int("LOCKOUT_DURATION_MINUTES", 1),
|
|
1662
|
+
verifySessionOnAuth: r.bool("VERIFY_SESSION_ON_AUTH"),
|
|
1663
|
+
systemTenantId: r.str("SYSTEM_TENANT_ID"),
|
|
1664
|
+
refreshTokenGraceWindowMs: r.int("REFRESH_TOKEN_GRACE_WINDOW_MS"),
|
|
1665
|
+
verificationResendCooldownSeconds: r.int("VERIFICATION_RESEND_COOLDOWN_SECONDS"),
|
|
1666
|
+
corsOrigins: r.list("CORS_ORIGINS"),
|
|
1667
|
+
dynamicOrigins: { enabled: r.bool("CORS_ORIGINS_DYNAMIC"), cacheSeconds: r.int("CORS_ORIGINS_CACHE_SECONDS", 1) },
|
|
1668
|
+
gatewaySecret: r.str("GATEWAY_SECRET"),
|
|
1669
|
+
ownershipTransferEnabled: r.bool("OWNERSHIP_TRANSFER_ENABLED"),
|
|
1670
|
+
securityNotificationsEnabled: r.bool("SECURITY_NOTIFICATIONS_ENABLED")
|
|
1671
|
+
},
|
|
1672
|
+
passwordEngine: readPasswordEngine(r),
|
|
1673
|
+
email: readEmail(r),
|
|
1674
|
+
oauth: {},
|
|
1675
|
+
features: { auditEnabled: r.bool("AUDIT_ENABLED"), deviceTracking: r.bool("DEVICE_TRACKING") },
|
|
1676
|
+
maintenance: r.bool("MAINTENANCE_MODE"),
|
|
1677
|
+
audit: { store: r.oneOf("AUDIT_STORE", ["log", "d1"]), retentionDays: r.int("AUDIT_RETENTION_DAYS", 1) },
|
|
1678
|
+
mfaSecretKeys: readMfaSecretKeys(r, env)
|
|
1679
|
+
};
|
|
1680
|
+
if (usesCookie(refreshTokenStrategy)) {
|
|
1681
|
+
config.auth.refreshTokenCookie = {
|
|
1682
|
+
name: r.str("REFRESH_TOKEN_COOKIE_NAME"),
|
|
1683
|
+
httpOnly: r.bool("REFRESH_TOKEN_COOKIE_HTTP_ONLY"),
|
|
1684
|
+
secure: r.bool("REFRESH_TOKEN_COOKIE_SECURE"),
|
|
1685
|
+
sameSite: r.oneOf("REFRESH_TOKEN_COOKIE_SAME_SITE", ["strict", "lax", "none"]),
|
|
1686
|
+
path: r.str("REFRESH_TOKEN_COOKIE_PATH"),
|
|
1687
|
+
...r.optional("REFRESH_TOKEN_COOKIE_MAX_AGE") && { maxAge: r.int("REFRESH_TOKEN_COOKIE_MAX_AGE") },
|
|
1688
|
+
...r.optional("REFRESH_TOKEN_COOKIE_DOMAIN") && { domain: r.str("REFRESH_TOKEN_COOKIE_DOMAIN") }
|
|
1689
|
+
};
|
|
1690
|
+
}
|
|
1691
|
+
if (config.security.refreshTokenGraceWindowMs > 12e4) {
|
|
1692
|
+
r.issues.push("REFRESH_TOKEN_GRACE_WINDOW_MS: at most 120000 (a replayed refresh token works that long)");
|
|
1693
|
+
}
|
|
1694
|
+
readAudiencesAndApps(r, config);
|
|
1695
|
+
readInternal(r, config);
|
|
1696
|
+
readOAuth(r, config);
|
|
1697
|
+
for (const problem of parseOriginPolicy(config.security.corsOrigins).problems) r.issues.push(problem);
|
|
1698
|
+
if (config.security.dynamicOrigins.cacheSeconds > 300) {
|
|
1699
|
+
r.issues.push("CORS_ORIGINS_CACHE_SECONDS: at most 300 (a removed origin stays allowed that long)");
|
|
1700
|
+
}
|
|
1701
|
+
if (r.optional("ALLOW_DIRECT_ACCESS") !== void 0) {
|
|
1702
|
+
r.issues.push("ALLOW_DIRECT_ACCESS: removed; the Worker is reached directly unless GATEWAY_SECRET is set");
|
|
1703
|
+
}
|
|
1704
|
+
if (r.issues.length > 0) {
|
|
1705
|
+
return err(configErrors.INVALID({ count: r.issues.length, details: r.issues.map((i) => ` - ${i}`).join("\n") }));
|
|
1706
|
+
}
|
|
1707
|
+
return ok(config);
|
|
1708
|
+
}
|
|
1709
|
+
function readPasswordEngine(r) {
|
|
1710
|
+
const raw = r.str("PASSWORD_ENGINE");
|
|
1711
|
+
if (raw === "") {
|
|
1712
|
+
r.issues.push("PASSWORD_ENGINE: required (local on Workers Paid, remote on Workers Free)");
|
|
1713
|
+
return { mode: "remote" };
|
|
1714
|
+
}
|
|
1715
|
+
const mode = r.oneOf("PASSWORD_ENGINE", ["local", "remote"]);
|
|
1716
|
+
if (mode === "local") return { mode };
|
|
1717
|
+
const url = r.required("PASSWORD_ENGINE_URL");
|
|
1718
|
+
if (url && !/^https:\/\//.test(url) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/.test(url)) {
|
|
1719
|
+
r.issues.push("PASSWORD_ENGINE_URL: must be https (passwords travel in the body)");
|
|
1720
|
+
}
|
|
1721
|
+
const signingKey = r.required("PASSWORD_ENGINE_SIGNING_KEY");
|
|
1722
|
+
if (signingKey) {
|
|
1723
|
+
try {
|
|
1724
|
+
const jwk = JSON.parse(signingKey);
|
|
1725
|
+
if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.d !== "string") {
|
|
1726
|
+
r.issues.push("PASSWORD_ENGINE_SIGNING_KEY: must be an Ed25519 private JWK");
|
|
1727
|
+
}
|
|
1728
|
+
} catch {
|
|
1729
|
+
r.issues.push("PASSWORD_ENGINE_SIGNING_KEY: must be JSON (Ed25519 private JWK)");
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
return {
|
|
1733
|
+
mode,
|
|
1734
|
+
url,
|
|
1735
|
+
signingKey,
|
|
1736
|
+
issuer: r.optional("PASSWORD_ENGINE_ISSUER") ?? r.str("AUTH_SYSTEM_NAME"),
|
|
1737
|
+
timeoutMs: r.int("PASSWORD_ENGINE_TIMEOUT_MS", 100)
|
|
1738
|
+
};
|
|
1739
|
+
}
|
|
1740
|
+
var EMAIL_FROM = /^\s*(?:[^<>\r\n]*<[^\s@<>]+@[^\s@<>]+>|[^\s@<>]+@[^\s@<>]+)\s*$/;
|
|
1741
|
+
function readEmail(r) {
|
|
1742
|
+
const mode = r.oneOf("EMAIL_MODE", ["console", "queue", "direct"]);
|
|
1743
|
+
const email = {
|
|
1744
|
+
mode,
|
|
1745
|
+
maxAgeMinutes: r.int("EMAIL_MAX_AGE_MINUTES", 1),
|
|
1746
|
+
retryBaseSeconds: r.int("EMAIL_RETRY_BASE_SECONDS", 0),
|
|
1747
|
+
inboundMaxBytes: r.int("EMAIL_INBOUND_MAX_BYTES", 1024),
|
|
1748
|
+
logRetentionDays: r.int("EMAIL_LOG_RETENTION_DAYS", 1)
|
|
1749
|
+
};
|
|
1750
|
+
const routes = r.optional("EMAIL_INBOUND_ROUTES");
|
|
1751
|
+
if (routes !== void 0) {
|
|
1752
|
+
const parsed = parseInboundRoutes(routes);
|
|
1753
|
+
if (parsed.ok) email.inboundRoutes = parsed.data;
|
|
1754
|
+
else r.issues.push(parsed.errors[0]?.message ?? "EMAIL_INBOUND_ROUTES: invalid");
|
|
1755
|
+
}
|
|
1756
|
+
const webhookSecret = r.optional("RESEND_WEBHOOK_SECRET");
|
|
1757
|
+
if (webhookSecret !== void 0) {
|
|
1758
|
+
if (/^whsec_[A-Za-z0-9+/=]{20,}$/.test(webhookSecret)) email.resendWebhookSecret = webhookSecret;
|
|
1759
|
+
else r.issues.push("RESEND_WEBHOOK_SECRET: must be the whsec_\u2026 signing secret");
|
|
1760
|
+
}
|
|
1761
|
+
if (mode === "console") return email;
|
|
1762
|
+
const raw = r.str("EMAIL_PROVIDER");
|
|
1763
|
+
if (raw === "") {
|
|
1764
|
+
r.issues.push(`EMAIL_PROVIDER: required with EMAIL_MODE=${mode} (resend | cloudflare | relay)`);
|
|
1765
|
+
return email;
|
|
1766
|
+
}
|
|
1767
|
+
email.provider = r.oneOf("EMAIL_PROVIDER", ["resend", "cloudflare", "relay"]);
|
|
1768
|
+
if (email.provider === "relay") {
|
|
1769
|
+
email.relay = readRelay(r);
|
|
1770
|
+
const from2 = r.optional("EMAIL_FROM");
|
|
1771
|
+
if (from2 !== void 0 && !EMAIL_FROM.test(from2))
|
|
1772
|
+
r.issues.push('EMAIL_FROM: must be an address or "Name <address>"');
|
|
1773
|
+
email.from = from2 ?? "";
|
|
1774
|
+
return email;
|
|
1775
|
+
}
|
|
1776
|
+
if (email.provider === "resend") email.resendApiKey = r.required("RESEND_API_KEY");
|
|
1777
|
+
const from = r.required("EMAIL_FROM");
|
|
1778
|
+
if (from && !EMAIL_FROM.test(from)) r.issues.push('EMAIL_FROM: must be an address or "Name <address>"');
|
|
1779
|
+
email.from = from;
|
|
1780
|
+
const replyTo = r.optional("EMAIL_REPLY_TO");
|
|
1781
|
+
if (replyTo !== void 0) {
|
|
1782
|
+
if (EMAIL_FROM.test(replyTo)) email.replyTo = replyTo;
|
|
1783
|
+
else r.issues.push("EMAIL_REPLY_TO: must be an email address");
|
|
1784
|
+
}
|
|
1785
|
+
return email;
|
|
1786
|
+
}
|
|
1787
|
+
function readRelay(r) {
|
|
1788
|
+
const url = r.required("EMAIL_RELAY_URL");
|
|
1789
|
+
if (url && !/^https:\/\//.test(url) && !/^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?(\/|$)/.test(url)) {
|
|
1790
|
+
r.issues.push("EMAIL_RELAY_URL: must be https (sign-in codes travel in the body)");
|
|
1791
|
+
}
|
|
1792
|
+
const signingKey = r.required("EMAIL_RELAY_SIGNING_KEY");
|
|
1793
|
+
if (signingKey) {
|
|
1794
|
+
try {
|
|
1795
|
+
const jwk = JSON.parse(signingKey);
|
|
1796
|
+
if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || typeof jwk.d !== "string") {
|
|
1797
|
+
r.issues.push("EMAIL_RELAY_SIGNING_KEY: must be an Ed25519 private JWK");
|
|
1798
|
+
}
|
|
1799
|
+
} catch {
|
|
1800
|
+
r.issues.push("EMAIL_RELAY_SIGNING_KEY: must be JSON (Ed25519 private JWK)");
|
|
1801
|
+
}
|
|
1802
|
+
}
|
|
1803
|
+
return {
|
|
1804
|
+
url,
|
|
1805
|
+
signingKey,
|
|
1806
|
+
issuer: r.optional("EMAIL_RELAY_ISSUER") ?? r.optional("PASSWORD_ENGINE_ISSUER") ?? r.str("AUTH_SYSTEM_NAME"),
|
|
1807
|
+
timeoutMs: r.int("EMAIL_RELAY_TIMEOUT_MS", 100)
|
|
1808
|
+
};
|
|
1809
|
+
}
|
|
1810
|
+
function readMfaSecretKeys(r, env) {
|
|
1811
|
+
const strings = {};
|
|
1812
|
+
for (const name of ["MFA_SECRET_KEY", "MFA_SECRET_KEY_ID", "MFA_SECRET_PREVIOUS_KEYS"]) {
|
|
1813
|
+
const value = env[name];
|
|
1814
|
+
if (typeof value === "string") strings[name] = value;
|
|
1815
|
+
}
|
|
1816
|
+
try {
|
|
1817
|
+
return totpSecretKeysFromEnv(strings);
|
|
1818
|
+
} catch {
|
|
1819
|
+
r.issues.push("MFA_SECRET_KEY / MFA_SECRET_PREVIOUS_KEYS: invalid key material");
|
|
1820
|
+
return null;
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
function readAudience(r, worker, lambda, label) {
|
|
1824
|
+
if (worker !== void 0 && lambda !== void 0 && worker !== lambda)
|
|
1825
|
+
r.issues.push(`${label}: set one (they differ)`);
|
|
1826
|
+
return worker ?? lambda;
|
|
1827
|
+
}
|
|
1828
|
+
function readAudiencesAndApps(r, config) {
|
|
1829
|
+
const customer = readAudience(
|
|
1830
|
+
r,
|
|
1831
|
+
r.optional("JWT_CUSTOMER_AUDIENCE"),
|
|
1832
|
+
r.optional("TOKEN_AUD_CUSTOMER"),
|
|
1833
|
+
"JWT_CUSTOMER_AUDIENCE / TOKEN_AUD_CUSTOMER"
|
|
1834
|
+
);
|
|
1835
|
+
const tenant = readAudience(
|
|
1836
|
+
r,
|
|
1837
|
+
r.optional("JWT_TENANT_AUDIENCE"),
|
|
1838
|
+
r.optional("TOKEN_AUD_TENANT"),
|
|
1839
|
+
"JWT_TENANT_AUDIENCE / TOKEN_AUD_TENANT"
|
|
1840
|
+
);
|
|
1841
|
+
const system = readAudience(
|
|
1842
|
+
r,
|
|
1843
|
+
r.optional("JWT_SYSTEM_AUDIENCE"),
|
|
1844
|
+
r.optional("TOKEN_AUD_SYSTEM"),
|
|
1845
|
+
"JWT_SYSTEM_AUDIENCE / TOKEN_AUD_SYSTEM"
|
|
1846
|
+
);
|
|
1847
|
+
const raw = r.optional("AUTH_APPS");
|
|
1848
|
+
const defaultApp = r.optional("AUTH_DEFAULT_APP");
|
|
1849
|
+
if (raw === void 0) {
|
|
1850
|
+
if (defaultApp !== void 0) r.issues.push("AUTH_DEFAULT_APP: needs AUTH_APPS");
|
|
1851
|
+
const audiences = { customer: customer ?? "customer", tenant: tenant ?? "tenant", system: system ?? "system" };
|
|
1852
|
+
const values = Object.values(audiences);
|
|
1853
|
+
if (new Set(values).size !== values.length) {
|
|
1854
|
+
r.issues.push("JWT_CUSTOMER_AUDIENCE / JWT_TENANT_AUDIENCE / JWT_SYSTEM_AUDIENCE: must differ");
|
|
1855
|
+
}
|
|
1856
|
+
const cookieNames = {
|
|
1857
|
+
customer: r.optional("REFRESH_COOKIE_CUSTOMER") ?? "refresh_token",
|
|
1858
|
+
tenant: r.optional("REFRESH_COOKIE_TENANT") ?? "refresh_token_tenant",
|
|
1859
|
+
system: r.optional("REFRESH_COOKIE_SYSTEM") ?? "refresh_token_system"
|
|
1860
|
+
};
|
|
1861
|
+
if (new Set(Object.values(cookieNames)).size !== 3) {
|
|
1862
|
+
r.issues.push("REFRESH_COOKIE_CUSTOMER / REFRESH_COOKIE_TENANT / REFRESH_COOKIE_SYSTEM: must differ");
|
|
1863
|
+
}
|
|
1864
|
+
if (r.explicit("REFRESH_TOKEN_COOKIE_NAME")) {
|
|
1865
|
+
r.issues.push(
|
|
1866
|
+
"REFRESH_TOKEN_COOKIE_NAME: not used by the customer / tenant / system apps; set REFRESH_COOKIE_CUSTOMER / _TENANT / _SYSTEM"
|
|
1867
|
+
);
|
|
1868
|
+
}
|
|
1869
|
+
config.security.tokenAudiences = { ...audiences, cookieNames };
|
|
1870
|
+
return;
|
|
1871
|
+
}
|
|
1872
|
+
const mixed = PRESET_APP_VARS.filter((name) => r.optional(name) !== void 0);
|
|
1873
|
+
if (mixed.length > 0) r.issues.push(`AUTH_APPS: cannot be combined with ${mixed.join(", ")}; set them per app`);
|
|
1874
|
+
let json;
|
|
1875
|
+
try {
|
|
1876
|
+
json = JSON.parse(raw);
|
|
1877
|
+
} catch {
|
|
1878
|
+
r.issues.push("AUTH_APPS: must be valid JSON");
|
|
1879
|
+
return;
|
|
1880
|
+
}
|
|
1881
|
+
const parsed = parseAppsConfig(json);
|
|
1882
|
+
for (const problem of parsed.errors) r.issues.push(`AUTH_APPS: ${problem}`);
|
|
1883
|
+
if (!parsed.apps) return;
|
|
1884
|
+
config.security.apps = parsed.apps;
|
|
1885
|
+
if (defaultApp !== void 0) config.security.defaultApp = defaultApp;
|
|
1886
|
+
for (const problem of validateApps({
|
|
1887
|
+
apps: parsed.apps,
|
|
1888
|
+
...defaultApp !== void 0 && { defaultApp },
|
|
1889
|
+
systemTenantId: config.security.systemTenantId
|
|
1890
|
+
})) {
|
|
1891
|
+
r.issues.push(`AUTH_APPS: ${problem}`);
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
function readInternal(r, config) {
|
|
1895
|
+
const key = r.optional("INTERNAL_JWT_PUBLIC_KEY");
|
|
1896
|
+
if (!key) return;
|
|
1897
|
+
const requiredRoles = r.list("INTERNAL_REQUIRED_ROLES");
|
|
1898
|
+
if (requiredRoles.length === 0)
|
|
1899
|
+
r.issues.push("INTERNAL_REQUIRED_ROLES: required when INTERNAL_JWT_PUBLIC_KEY is set");
|
|
1900
|
+
config.internal = {
|
|
1901
|
+
publicKeyJwk: key,
|
|
1902
|
+
alg: r.oneOf("SERVICE_JWT_ALGORITHM", ["EdDSA", "ES256", "RS256", "PS256"]),
|
|
1903
|
+
issuer: r.str("INTERNAL_JWT_ISSUER"),
|
|
1904
|
+
audience: r.str("INTERNAL_JWT_AUDIENCE"),
|
|
1905
|
+
routePath: normalizePath(r.str("SERVICE_ROUTE_PATH")),
|
|
1906
|
+
requiredRoles
|
|
1907
|
+
};
|
|
1908
|
+
const countryCode = r.optional("PHONE_DEFAULT_COUNTRY_CODE");
|
|
1909
|
+
if (countryCode !== void 0) {
|
|
1910
|
+
if (/^[1-9]\d{0,2}$/.test(countryCode)) config.internal.phoneDefaultCountryCode = countryCode;
|
|
1911
|
+
else r.issues.push("PHONE_DEFAULT_COUNTRY_CODE: must be 1-3 digits without + (e.g. 84)");
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
function readOAuth(r, config) {
|
|
1915
|
+
const fbId = r.optional("FACEBOOK_CLIENT_ID");
|
|
1916
|
+
const fbSecret = r.optional("FACEBOOK_CLIENT_SECRET");
|
|
1917
|
+
if (fbId && fbSecret) {
|
|
1918
|
+
config.oauth.facebook = { clientId: fbId, clientSecret: fbSecret, redirectUri: r.str("FACEBOOK_REDIRECT_URI") };
|
|
1919
|
+
}
|
|
1920
|
+
const googleId = r.optional("GOOGLE_CLIENT_ID");
|
|
1921
|
+
const googleSecret = r.optional("GOOGLE_CLIENT_SECRET");
|
|
1922
|
+
const prompt = r.optional("GOOGLE_PROMPT") === void 0 ? void 0 : r.oneOf("GOOGLE_PROMPT", ["consent", "select_account"]);
|
|
1923
|
+
if (googleId && googleSecret) {
|
|
1924
|
+
config.oauth.google = {
|
|
1925
|
+
clientId: googleId,
|
|
1926
|
+
clientSecret: googleSecret,
|
|
1927
|
+
redirectUri: r.str("GOOGLE_REDIRECT_URI"),
|
|
1928
|
+
...prompt && { prompt }
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
}
|
|
1932
|
+
export {
|
|
1933
|
+
configErrors,
|
|
1934
|
+
loadWorkerConfig
|
|
1935
|
+
};
|