@aooth/auth-moost 0.1.84 → 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/dist/atscript/index.d.mts +42 -27
- package/dist/atscript/index.mjs +2 -2
- package/dist/{forms-B9-r2zT5.mjs → forms-C9Wey0e9.mjs} +14 -4
- package/dist/index.d.mts +358 -24
- package/dist/index.mjs +801 -330
- package/package.json +9 -9
- package/src/atscript/models/forms.as +26 -6
- package/src/atscript/models/forms.as.d.ts +42 -26
package/dist/index.mjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import { C as
|
|
1
|
+
import { C as RemoveMfaConfirmForm, D as StepUpConfirmForm, E as SignupForm, O as TermsBumpForm, T as SetPasswordForm, _ as PasswordReauthForm, a as ConcurrencyLimitForm, b as ProveControlOtpForm, c as EnrollConfirmForm, d as InviteChooseUsernameForm, f as InviteForm, g as MfaCodeForm, h as ManageMfaForm, i as ChangePasswordForm, l as EnrollPickMethodForm, n as AskPhoneForm, o as EmailIdentifierForm, p as LoginCredentialsForm, r as AuthorizeConsentForm, s as EnrollAddressForm, t as AskEmailForm, u as EnrollTotpQrForm, v as PincodeForm, w as Select2faForm, y as ProveControlForm } from "./forms-C9Wey0e9.mjs";
|
|
2
2
|
import { Controller, HandlerPaths, Inherit, Inject, InjectMoostLogger, Injectable, Intercept, MoostInit, Optional, Param, Resolve, TInterceptorPriority, defineAfterInterceptor, defineBeforeInterceptor, getMoostMate, useControllerContext, useLogger } from "moost";
|
|
3
|
-
import { AuthCredential, AuthError, RateLimitStoreMemory, RateLimiter, RateLimiter as RateLimiter$1, generateMagicLinkToken, generateOpaqueToken, parseRateLimitRule } from "@aooth/auth";
|
|
3
|
+
import { AuthCredential, AuthError, RateLimitStoreMemory, RateLimitStoreMemory as RateLimitStoreMemory$1, RateLimiter, RateLimiter as RateLimiter$1, generateMagicLinkToken, generateOpaqueToken, parseRateLimitRule, pickGoverning } from "@aooth/auth";
|
|
4
4
|
import { current, defineWook, eventTypeKey, key } from "@wooksjs/event-core";
|
|
5
5
|
import { HttpError, useAuthorization, useCookies, useHeaders, useRequest, useResponse, useUrlParams } from "@wooksjs/event-http";
|
|
6
6
|
import { ArbacAction, ArbacResource, getArbacMate, useArbac } from "@aooth/arbac-moost";
|
|
7
7
|
import { FederatedIdentityStore, SEEN_DEVICES_DEFAULT_CAP, UserAuthError, UserService, generateMfaCode, generateTotpSecret, generateTotpUri, maskEmail, maskPhone, pickDefinedProfile, verifyTotpCode } from "@aooth/user";
|
|
8
8
|
import { Body, Delete, Get, HttpError as HttpError$1, Post, Query } from "@moostjs/event-http";
|
|
9
|
-
import { createHash, timingSafeEqual } from "node:crypto";
|
|
9
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
10
10
|
import { createAsHttpOutlet, finishWf, handleAsOutletRequest, useAtscriptWf } from "@atscript/moost-wf";
|
|
11
|
-
import { EncapsulatedStateStrategy, MoostWf, Step, StepRetriableError, StepTTL, Workflow, WorkflowParam, WorkflowSchema, createEmailOutlet, outletEmail, swapStrategy, useWfFinished, useWfState } from "@moostjs/event-wf";
|
|
11
|
+
import { EncapsulatedStateStrategy, MoostWf, Step, StepRetriableError, StepTTL, Workflow, WorkflowParam, WorkflowSchema, createEmailOutlet, outlet, outletEmail, swapStrategy, useWfFinished, useWfState } from "@moostjs/event-wf";
|
|
12
12
|
import { FederatedLoginService, OAuthError, OAuthProviderRegistry, generateRandomState, pkceChallengeFor } from "@aooth/idp";
|
|
13
13
|
import { ClientRegistrationError, DynamicClientRegistration, NoopOidcClaimsResolver, buildAuthorizationServerMetadata, buildAuthorizationServerMetadata as buildAuthorizationServerMetadata$1, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, canonicalizeIssuer as canonicalizeIssuer$1, tokenPolicyToIssueOptions } from "@aooth/auth/authz";
|
|
14
14
|
//#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorate.js
|
|
@@ -75,21 +75,26 @@ function resolveAuthOptions(opts = {}) {
|
|
|
75
75
|
sameSite: "lax",
|
|
76
76
|
httpOnly: true,
|
|
77
77
|
path: "/",
|
|
78
|
+
persistent: false,
|
|
78
79
|
...opts.cookie
|
|
79
80
|
};
|
|
81
|
+
const refreshCookie = {
|
|
82
|
+
name: "aooth_refresh",
|
|
83
|
+
secure: cookie.secure,
|
|
84
|
+
sameSite: cookie.sameSite,
|
|
85
|
+
httpOnly: cookie.httpOnly,
|
|
86
|
+
...cookie.domain !== void 0 && { domain: cookie.domain },
|
|
87
|
+
path: "/auth/refresh",
|
|
88
|
+
persistent: false,
|
|
89
|
+
...opts.refreshCookie
|
|
90
|
+
};
|
|
91
|
+
const enableCookie = opts.enableCookie ?? true;
|
|
80
92
|
return {
|
|
81
93
|
cookie,
|
|
82
|
-
refreshCookie
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
httpOnly: cookie.httpOnly,
|
|
87
|
-
...cookie.domain !== void 0 && { domain: cookie.domain },
|
|
88
|
-
path: "/auth/refresh",
|
|
89
|
-
...opts.refreshCookie
|
|
90
|
-
},
|
|
91
|
-
enableCookie: opts.enableCookie ?? true,
|
|
92
|
-
enableBearer: opts.enableBearer ?? true
|
|
94
|
+
refreshCookie,
|
|
95
|
+
enableCookie,
|
|
96
|
+
enableBearer: opts.enableBearer ?? true,
|
|
97
|
+
exposeTokensInBody: opts.exposeTokensInBody ?? !enableCookie
|
|
93
98
|
};
|
|
94
99
|
}
|
|
95
100
|
//#endregion
|
|
@@ -104,6 +109,15 @@ const authCredentialKey = key("auth.credential");
|
|
|
104
109
|
*/
|
|
105
110
|
const authOptionsKey = key("auth.options");
|
|
106
111
|
/**
|
|
112
|
+
* `Max-Age` for a persistent cookie carrying a token that expires at
|
|
113
|
+
* `expiresAt` (ms epoch). A unit-explicit `'<n>s'` string — wooks reads a
|
|
114
|
+
* bare number differently across versions.
|
|
115
|
+
*/
|
|
116
|
+
function persistFor(c, expiresAt) {
|
|
117
|
+
if (!c.persistent || expiresAt === void 0) return void 0;
|
|
118
|
+
return { maxAge: `${Math.max(0, Math.floor((expiresAt - Date.now()) / 1e3))}s` };
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
107
121
|
* `sameSite` is upper-cased because wooks accepts `'Lax' | 'Strict' | 'None'`
|
|
108
122
|
* while `ResolvedAuthCookieConfig` stores lower-case for ergonomics.
|
|
109
123
|
*
|
|
@@ -174,12 +188,29 @@ const useAuth = defineWook((ctx) => {
|
|
|
174
188
|
if (!token && options.enableCookie) token = useCookies(ctx).getCookie(options.cookie.name) ?? void 0;
|
|
175
189
|
return token;
|
|
176
190
|
};
|
|
177
|
-
|
|
191
|
+
/**
|
|
192
|
+
* Build the `cookies` map for `useWfFinished({ cookies })`. The outlet
|
|
193
|
+
* trigger's HTTP layer turns the entries into `Set-Cookie` headers, mirroring
|
|
194
|
+
* what `writeCookies()` does for the REST controller.
|
|
195
|
+
*/
|
|
196
|
+
const buildFinishedCookies = (issue) => {
|
|
178
197
|
const options = requireOptions();
|
|
179
|
-
if (!options.enableCookie) return;
|
|
198
|
+
if (!options.enableCookie) return void 0;
|
|
199
|
+
const cookies = { [options.cookie.name]: {
|
|
200
|
+
value: issue.accessToken,
|
|
201
|
+
options: cookieAttrsFrom(options.cookie, persistFor(options.cookie, issue.accessExpiresAt))
|
|
202
|
+
} };
|
|
203
|
+
if (issue.refreshToken) cookies[options.refreshCookie.name] = {
|
|
204
|
+
value: issue.refreshToken,
|
|
205
|
+
options: cookieAttrsFrom(options.refreshCookie, persistFor(options.refreshCookie, issue.refreshExpiresAt))
|
|
206
|
+
};
|
|
207
|
+
return cookies;
|
|
208
|
+
};
|
|
209
|
+
const writeCookies = (issue) => {
|
|
210
|
+
const cookies = buildFinishedCookies(issue);
|
|
211
|
+
if (!cookies) return;
|
|
180
212
|
const response = useResponse(current());
|
|
181
|
-
response.setCookie(
|
|
182
|
-
if (issue.refreshToken) response.setCookie(options.refreshCookie.name, issue.refreshToken, cookieAttrsFrom(options.refreshCookie));
|
|
213
|
+
for (const [name, cookie] of Object.entries(cookies)) response.setCookie(name, cookie.value, cookie.options);
|
|
183
214
|
};
|
|
184
215
|
const clearCookies = () => {
|
|
185
216
|
const options = requireOptions();
|
|
@@ -189,40 +220,24 @@ const useAuth = defineWook((ctx) => {
|
|
|
189
220
|
response.setCookie(options.refreshCookie.name, "", cookieAttrsFrom(options.refreshCookie, { maxAge: 0 }));
|
|
190
221
|
};
|
|
191
222
|
/**
|
|
192
|
-
* With `
|
|
193
|
-
* `accessExpiresAt` so clients can schedule a silent
|
|
194
|
-
* themselves travel only via the cookies set by
|
|
223
|
+
* With `exposeTokensInBody === false` (the cookie default) the response shape
|
|
224
|
+
* still carries `userId` + `accessExpiresAt` so clients can schedule a silent
|
|
225
|
+
* refresh, but the tokens themselves travel only via the cookies set by
|
|
226
|
+
* `writeCookies`.
|
|
195
227
|
*/
|
|
196
|
-
const buildLoginResponseFn = (userId, issue) => {
|
|
228
|
+
const buildLoginResponseFn = (userId, issue, opts) => {
|
|
197
229
|
const options = requireOptions();
|
|
230
|
+
const expose = opts?.exposeTokens ?? options.exposeTokensInBody;
|
|
198
231
|
return {
|
|
199
232
|
userId,
|
|
200
233
|
accessExpiresAt: issue.accessExpiresAt,
|
|
201
234
|
...issue.refreshExpiresAt !== void 0 && { refreshExpiresAt: issue.refreshExpiresAt },
|
|
202
|
-
...
|
|
235
|
+
...expose && {
|
|
203
236
|
accessToken: issue.accessToken,
|
|
204
237
|
...issue.refreshToken && { refreshToken: issue.refreshToken }
|
|
205
238
|
}
|
|
206
239
|
};
|
|
207
240
|
};
|
|
208
|
-
/**
|
|
209
|
-
* Build the `cookies` map for `useWfFinished({ cookies })`. The outlet
|
|
210
|
-
* trigger's HTTP layer turns the entries into `Set-Cookie` headers, mirroring
|
|
211
|
-
* what `writeCookies()` does for the REST controller.
|
|
212
|
-
*/
|
|
213
|
-
const buildFinishedCookies = (issue) => {
|
|
214
|
-
const options = requireOptions();
|
|
215
|
-
if (!options.enableCookie) return void 0;
|
|
216
|
-
const cookies = { [options.cookie.name]: {
|
|
217
|
-
value: issue.accessToken,
|
|
218
|
-
options: cookieAttrsFrom(options.cookie)
|
|
219
|
-
} };
|
|
220
|
-
if (issue.refreshToken) cookies[options.refreshCookie.name] = {
|
|
221
|
-
value: issue.refreshToken,
|
|
222
|
-
options: cookieAttrsFrom(options.refreshCookie)
|
|
223
|
-
};
|
|
224
|
-
return cookies;
|
|
225
|
-
};
|
|
226
241
|
const cookieAttrs = (extra) => {
|
|
227
242
|
return cookieAttrsFrom(requireOptions().cookie, extra);
|
|
228
243
|
};
|
|
@@ -378,6 +393,250 @@ const Public = () => {
|
|
|
378
393
|
*/
|
|
379
394
|
const UserId = () => Resolve(() => useAuth().getUserId());
|
|
380
395
|
//#endregion
|
|
396
|
+
//#region src/rate-limit/composables.ts
|
|
397
|
+
/**
|
|
398
|
+
* Internal: the governing decision for this event (across every policy
|
|
399
|
+
* evaluated so far), written by `rateLimitInterceptors`.
|
|
400
|
+
*/
|
|
401
|
+
const rateLimitDecisionKey = key("aooth.rateLimit.decision");
|
|
402
|
+
/** Internal: phases (`pre` / `post`) that already evaluated this event — the double-count guard. */
|
|
403
|
+
const rateLimitPhasesKey = key("aooth.rateLimit.phases");
|
|
404
|
+
/**
|
|
405
|
+
* Internal: named rate-limit subjects for this event — subject kind
|
|
406
|
+
* (`'user'`, `'tenant'`, …) → resolved caller identity, written via
|
|
407
|
+
* {@link setRateLimitSubject} and read by the post-guard rate-limit phase.
|
|
408
|
+
*/
|
|
409
|
+
const rateLimitSubjectsKey = key("aooth.rateLimit.subjects");
|
|
410
|
+
/**
|
|
411
|
+
* Supply the rate-limit subject for a named key strategy — the seam for
|
|
412
|
+
* custom IAMs / tenant resolvers. Call from GUARD-priority (or earlier)
|
|
413
|
+
* code; the value is used VERBATIM as the counter subject (include your own
|
|
414
|
+
* prefix, e.g. `iam:<sub>`) and always wins over the built-in `user` /
|
|
415
|
+
* `session` derivations. Full contract: docs `/moost/rate-limit`.
|
|
416
|
+
*/
|
|
417
|
+
function setRateLimitSubject(kind, subject, ctx = current()) {
|
|
418
|
+
const subjects = ctx.has(rateLimitSubjectsKey) ? ctx.get(rateLimitSubjectsKey) : {};
|
|
419
|
+
subjects[kind] = subject;
|
|
420
|
+
ctx.set(rateLimitSubjectsKey, subjects);
|
|
421
|
+
}
|
|
422
|
+
/** Read a named rate-limit subject set for this event (or `undefined`). */
|
|
423
|
+
function getRateLimitSubject(kind, ctx = current()) {
|
|
424
|
+
return ctx.has(rateLimitSubjectsKey) ? ctx.get(rateLimitSubjectsKey)[kind] : void 0;
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Read the current event's rate-limit state. A plain function (not a cached
|
|
428
|
+
* wook) — it's a single slot read, and workflow child events inherit the
|
|
429
|
+
* HTTP parent's slot transparently.
|
|
430
|
+
*/
|
|
431
|
+
function useRateLimit(ctx = current()) {
|
|
432
|
+
return { decision: ctx.has(rateLimitDecisionKey) ? ctx.get(rateLimitDecisionKey) : null };
|
|
433
|
+
}
|
|
434
|
+
//#endregion
|
|
435
|
+
//#region src/rate-limit/interceptor.ts
|
|
436
|
+
/**
|
|
437
|
+
* Global interceptor PAIR enforcing `@RateLimit` metadata (RL.spec.md §5.2)
|
|
438
|
+
* — register with spread:
|
|
439
|
+
*
|
|
440
|
+
* ```ts
|
|
441
|
+
* app.applyGlobalInterceptors(
|
|
442
|
+
* authGuardInterceptor({ ... }),
|
|
443
|
+
* ...rateLimitInterceptors({ limiter, trustProxy: true }),
|
|
444
|
+
* )
|
|
445
|
+
* ```
|
|
446
|
+
*
|
|
447
|
+
* Two phases, because the primary target is public endpoints and
|
|
448
|
+
* `authGuardInterceptor` is NOT free there — with any `Authorization`
|
|
449
|
+
* header present it runs full credential validation before tolerating the
|
|
450
|
+
* failure on `@Public()` routes:
|
|
451
|
+
*
|
|
452
|
+
* - `BEFORE_GUARD` phase owns routes whose effective key strategy is
|
|
453
|
+
* `'ip'` or a custom resolver — floods are rejected before any
|
|
454
|
+
* token/credential work.
|
|
455
|
+
* - `AFTER_GUARD` phase owns `'user'` / `'auto'` keyed routes — those need
|
|
456
|
+
* the auth context `useAuth()` reads, and by definition target
|
|
457
|
+
* authenticated traffic where the guard must run anyway.
|
|
458
|
+
*
|
|
459
|
+
* Ownership is static per policy (from metadata/options): a route whose
|
|
460
|
+
* stacked policies mix both kinds is evaluated by both phases, each checking
|
|
461
|
+
* its own policies. A per-event phase marker guards against double counting
|
|
462
|
+
* when the pair is also attached per-controller (see {@link RateLimited}).
|
|
463
|
+
*
|
|
464
|
+
* On rejection: draft `RateLimit-*` headers + `Retry-After` are written to
|
|
465
|
+
* the accumulated response (they survive the throw — wooks renders the error
|
|
466
|
+
* onto the same `HttpResponse`), then `HttpError(429, message)` is thrown.
|
|
467
|
+
*/
|
|
468
|
+
function rateLimitInterceptors(opts) {
|
|
469
|
+
const defaultRules = opts?.rules?.map((r) => parseRateLimitRule(r));
|
|
470
|
+
const limiter = opts?.limiter ?? new RateLimiter$1();
|
|
471
|
+
const emitHeaders = opts?.headers ?? true;
|
|
472
|
+
const ipOpts = { trustProxy: opts?.trustProxy ?? false };
|
|
473
|
+
const routeConfigs = /* @__PURE__ */ new WeakMap();
|
|
474
|
+
const resolveRouteConfig = (cc) => {
|
|
475
|
+
const ctor = cc.getController().constructor;
|
|
476
|
+
const method = String(cc.getMethod());
|
|
477
|
+
let byMethod = routeConfigs.get(ctor);
|
|
478
|
+
if (!byMethod) {
|
|
479
|
+
byMethod = /* @__PURE__ */ new Map();
|
|
480
|
+
routeConfigs.set(ctor, byMethod);
|
|
481
|
+
}
|
|
482
|
+
const cached = byMethod.get(method);
|
|
483
|
+
if (cached !== void 0) return cached;
|
|
484
|
+
const cMeta = cc.getControllerMeta();
|
|
485
|
+
const mMeta = cc.getMethodMeta();
|
|
486
|
+
let config = null;
|
|
487
|
+
const disabled = mMeta?.rateLimitDisabled ?? cMeta?.rateLimitDisabled ?? false;
|
|
488
|
+
const declared = mMeta?.rateLimitPolicies ?? cMeta?.rateLimitPolicies ?? (defaultRules && defaultRules.length > 0 ? [{ rules: defaultRules }] : void 0);
|
|
489
|
+
if (!disabled && declared && declared.length > 0) {
|
|
490
|
+
const baseScope = `${ctor.name}.${method}`;
|
|
491
|
+
const route = {
|
|
492
|
+
pre: [],
|
|
493
|
+
post: []
|
|
494
|
+
};
|
|
495
|
+
for (const [i, policy] of declared.entries()) {
|
|
496
|
+
const rawKey = policy.options?.key ?? opts?.key ?? "ip";
|
|
497
|
+
const keyStrategy = rawKey === "auto" ? "user" : rawKey;
|
|
498
|
+
const message = policy.options?.message ?? opts?.message;
|
|
499
|
+
route[typeof keyStrategy === "string" && keyStrategy !== "ip" ? "post" : "pre"].push({
|
|
500
|
+
rules: policy.rules,
|
|
501
|
+
keyStrategy,
|
|
502
|
+
scope: policy.options?.id ?? (i === 0 ? baseScope : `${baseScope}#${i}`),
|
|
503
|
+
...message !== void 0 && { defaultMessage: message },
|
|
504
|
+
policyHeader: policy.rules.map((p) => `${p.limit};w=${Math.max(1, Math.round(p.window / 1e3))}`).join(", ")
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
config = route;
|
|
508
|
+
}
|
|
509
|
+
byMethod.set(method, config);
|
|
510
|
+
return config;
|
|
511
|
+
};
|
|
512
|
+
const evaluate = async (phase) => {
|
|
513
|
+
const ctx = current();
|
|
514
|
+
if (ctx.get(eventTypeKey) !== "http") return;
|
|
515
|
+
const done = ctx.has(rateLimitPhasesKey) ? ctx.get(rateLimitPhasesKey) : [];
|
|
516
|
+
if (done.includes(phase)) return;
|
|
517
|
+
const config = resolveRouteConfig(useControllerContext(ctx));
|
|
518
|
+
if (!config) return;
|
|
519
|
+
const owned = config[phase];
|
|
520
|
+
if (owned.length === 0) return;
|
|
521
|
+
ctx.set(rateLimitPhasesKey, [...done, phase]);
|
|
522
|
+
const decisions = [];
|
|
523
|
+
const headers = [];
|
|
524
|
+
for (const policy of owned) {
|
|
525
|
+
const subject = await resolveSubject(policy.keyStrategy, ipOpts, ctx);
|
|
526
|
+
if (subject == null) continue;
|
|
527
|
+
decisions.push(await limiter.check(policy.scope, subject, policy.rules, { ...policy.defaultMessage !== void 0 && { defaultMessage: policy.defaultMessage } }));
|
|
528
|
+
headers.push(policy.policyHeader);
|
|
529
|
+
}
|
|
530
|
+
if (ctx.has(rateLimitDecisionKey)) decisions.unshift(ctx.get(rateLimitDecisionKey));
|
|
531
|
+
if (decisions.length === 0) return;
|
|
532
|
+
const decision = pickGoverning(decisions, (d) => !d.allowed);
|
|
533
|
+
ctx.set(rateLimitDecisionKey, decision);
|
|
534
|
+
const response = useResponse(ctx);
|
|
535
|
+
if (emitHeaders) {
|
|
536
|
+
const prior = response.getHeader("ratelimit-policy");
|
|
537
|
+
if (typeof prior === "string" && prior) headers.unshift(prior);
|
|
538
|
+
response.setHeader("ratelimit-limit", String(decision.limit));
|
|
539
|
+
response.setHeader("ratelimit-remaining", String(decision.remaining));
|
|
540
|
+
response.setHeader("ratelimit-reset", String(Math.ceil(decision.resetAfterMs / 1e3)));
|
|
541
|
+
response.setHeader("ratelimit-policy", headers.join(", "));
|
|
542
|
+
}
|
|
543
|
+
if (!decision.allowed) {
|
|
544
|
+
response.setHeader("retry-after", String(Math.ceil(decision.resetAfterMs / 1e3)));
|
|
545
|
+
throw new HttpError(429, decision.message ?? "Too many requests");
|
|
546
|
+
}
|
|
547
|
+
};
|
|
548
|
+
return [defineBeforeInterceptor(() => evaluate("pre"), TInterceptorPriority.BEFORE_GUARD), defineBeforeInterceptor(() => evaluate("post"), TInterceptorPriority.AFTER_GUARD)];
|
|
549
|
+
}
|
|
550
|
+
async function resolveSubject(strategy, ipOpts, ctx) {
|
|
551
|
+
if (typeof strategy === "function") return await strategy();
|
|
552
|
+
if (strategy !== "ip") {
|
|
553
|
+
const subject = getRateLimitSubject(strategy, ctx);
|
|
554
|
+
if (subject !== void 0) return subject;
|
|
555
|
+
const auth = strategy === "user" || strategy === "session" ? useAuth(ctx).getAuthContext() : null;
|
|
556
|
+
if (strategy === "user" && auth?.userId !== void 0) return `u:${auth.userId}`;
|
|
557
|
+
if (strategy === "session" && auth?.sessionId !== void 0) return `s:${auth.sessionId}`;
|
|
558
|
+
}
|
|
559
|
+
return `ip:${useRequest(ctx).getIp(ipOpts)}`;
|
|
560
|
+
}
|
|
561
|
+
//#endregion
|
|
562
|
+
//#region src/rate-limit/mate.ts
|
|
563
|
+
function getRateLimitMate() {
|
|
564
|
+
return getMoostMate();
|
|
565
|
+
}
|
|
566
|
+
//#endregion
|
|
567
|
+
//#region src/rate-limit/decorator.ts
|
|
568
|
+
function RateLimit(...args) {
|
|
569
|
+
const mate = getRateLimitMate();
|
|
570
|
+
if (args.length === 1 && args[0] === false) return mate.decorate("rateLimitDisabled", true);
|
|
571
|
+
const inputs = [...args];
|
|
572
|
+
let options;
|
|
573
|
+
const last = inputs[inputs.length - 1];
|
|
574
|
+
if (typeof last === "object" && last !== null && !("limit" in last)) options = inputs.pop();
|
|
575
|
+
if (inputs.length === 0) throw new Error("@RateLimit requires at least one rule (or the literal `false` to opt out)");
|
|
576
|
+
const rules = inputs.map((r) => parseRateLimitRule(r));
|
|
577
|
+
const policy = options ? {
|
|
578
|
+
rules,
|
|
579
|
+
options
|
|
580
|
+
} : { rules };
|
|
581
|
+
return mate.decorate((meta) => {
|
|
582
|
+
meta.rateLimitPolicies = [policy, ...meta.rateLimitPolicies ?? []];
|
|
583
|
+
return meta;
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* Decorator-factory sugar for attaching the `rateLimitInterceptors(opts)`
|
|
588
|
+
* PAIR to a specific controller or method instead of globally — the
|
|
589
|
+
* `AuthGuarded` counterpart. Attaching the pair (not one phase) matters:
|
|
590
|
+
* dropping the pre-guard def loses flood protection for ip-keyed routes,
|
|
591
|
+
* dropping the post-guard def silently disables `key: 'user'` routes.
|
|
592
|
+
*/
|
|
593
|
+
function RateLimited(opts) {
|
|
594
|
+
const [pre, post] = rateLimitInterceptors(opts);
|
|
595
|
+
const interceptPre = Intercept(pre);
|
|
596
|
+
const interceptPost = Intercept(post);
|
|
597
|
+
return ((target, key, descriptor) => {
|
|
598
|
+
interceptPre(target, key, descriptor);
|
|
599
|
+
interceptPost(target, key, descriptor);
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
//#endregion
|
|
603
|
+
//#region src/workflow/invite-outlet.ts
|
|
604
|
+
/** Name of the outlet `AuthWorkflow` pauses on for `inviteDelivery: 'deliver' | 'return-link'`. */
|
|
605
|
+
const INVITE_OUTLET = "invite";
|
|
606
|
+
const pendingInviteLinkKey = key("aooth.invite.pendingLink");
|
|
607
|
+
/**
|
|
608
|
+
* Trigger side: reserve the slot on the HTTP event before the workflow runs.
|
|
609
|
+
* Workflow steps run in a child event, and a child's write lands in the
|
|
610
|
+
* nearest context already holding the slot — so the step's callback becomes
|
|
611
|
+
* visible to the `invite` outlet, which runs back on the HTTP event.
|
|
612
|
+
*/
|
|
613
|
+
function reservePendingInviteLink() {
|
|
614
|
+
current().set(pendingInviteLinkKey, null);
|
|
615
|
+
}
|
|
616
|
+
/** Step side: register what to do with the token once the pause is persisted. */
|
|
617
|
+
function setPendingInviteLink(fn) {
|
|
618
|
+
current().set(pendingInviteLinkKey, fn);
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* The `invite` outlet (registered by default on `WfTriggerProvider`): hands
|
|
622
|
+
* the resume token to the callback the `send-email` step registered, which
|
|
623
|
+
* builds the link and delivers it (`'deliver'`) or returns it to the issuer
|
|
624
|
+
* (`'return-link'`). The token never rides the response on its own.
|
|
625
|
+
*/
|
|
626
|
+
function createInviteOutlet() {
|
|
627
|
+
return {
|
|
628
|
+
name: INVITE_OUTLET,
|
|
629
|
+
tokenDelivery: "out-of-band",
|
|
630
|
+
async deliver(_request, token) {
|
|
631
|
+
const ctx = current();
|
|
632
|
+
const pending = ctx.has(pendingInviteLinkKey) ? ctx.get(pendingInviteLinkKey) : null;
|
|
633
|
+
if (!pending) throw new Error("The invite outlet has no pending link — the trigger must run through WfTriggerProvider.handle()");
|
|
634
|
+
ctx.set(pendingInviteLinkKey, null);
|
|
635
|
+
return { response: await pending(token) };
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
//#endregion
|
|
381
640
|
//#region \0@oxc-project+runtime@0.140.0/helpers/esm/decorateMetadata.js
|
|
382
641
|
function __decorateMetadata(k, v) {
|
|
383
642
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
@@ -410,10 +669,39 @@ function __decorateMetadata(k, v) {
|
|
|
410
669
|
function deriveWfStateSecret(secret) {
|
|
411
670
|
return createHash("sha256").update(secret).digest();
|
|
412
671
|
}
|
|
672
|
+
/** One canonical workflow-id form for allow-list matching: no leading `/`. */
|
|
673
|
+
function normalizeWfId(id) {
|
|
674
|
+
return id.replace(/^\/+/, "");
|
|
675
|
+
}
|
|
676
|
+
function notAllowed(id) {
|
|
677
|
+
return new HttpError(403, `Workflow '${normalizeWfId(id)}' is not allowed`);
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* Wrap a strategy so a resume is checked against the allow list BEFORE the
|
|
681
|
+
* state is consumed: the state is peeked (`retrieve`), refused with 403 when
|
|
682
|
+
* its workflow is not allowed on this route (the token stays usable on its
|
|
683
|
+
* own route), and only then consumed.
|
|
684
|
+
*/
|
|
685
|
+
function guardStrategy(strategy, permits) {
|
|
686
|
+
return {
|
|
687
|
+
persist: (state, options, overrides) => strategy.persist(state, options, overrides),
|
|
688
|
+
retrieve: (token) => strategy.retrieve(token),
|
|
689
|
+
consume: async (token) => {
|
|
690
|
+
const peeked = await strategy.retrieve(token);
|
|
691
|
+
if (peeked && !permits(peeked.schemaId)) throw notAllowed(peeked.schemaId);
|
|
692
|
+
return strategy.consume(token);
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
}
|
|
413
696
|
let WfTriggerProvider = class WfTriggerProvider {
|
|
414
697
|
wf;
|
|
415
698
|
auth;
|
|
416
|
-
|
|
699
|
+
/**
|
|
700
|
+
* Outlets the trigger can pause on: HTTP (forms) and `invite` (the link of
|
|
701
|
+
* `AuthWorkflowOpts.inviteDelivery: 'deliver' | 'return-link'`). Append an
|
|
702
|
+
* `email` outlet (`createAuthEmailOutlet`) for the default invite delivery.
|
|
703
|
+
*/
|
|
704
|
+
outlets = [createAsHttpOutlet(), createInviteOutlet()];
|
|
417
705
|
token = {
|
|
418
706
|
read: [
|
|
419
707
|
"body",
|
|
@@ -463,23 +751,42 @@ let WfTriggerProvider = class WfTriggerProvider {
|
|
|
463
751
|
};
|
|
464
752
|
return this.cachedState;
|
|
465
753
|
}
|
|
754
|
+
/**
|
|
755
|
+
* Handle one trigger request. `allow` lists the workflow ids this route may
|
|
756
|
+
* START and RESUME (matched without a leading `/`); omitted = unrestricted,
|
|
757
|
+
* `[]` = deny all. A state token minted for a workflow outside the list is
|
|
758
|
+
* refused with 403 before it is consumed.
|
|
759
|
+
*/
|
|
466
760
|
async handle(opts = {}) {
|
|
467
761
|
const wfApp = this.wf.getWfApp();
|
|
762
|
+
const allowed = opts.allow && new Set(opts.allow.map(normalizeWfId));
|
|
763
|
+
const permits = (schemaId) => !allowed || allowed.has(normalizeWfId(schemaId));
|
|
764
|
+
const registry = this.stateRegistry();
|
|
765
|
+
const stateConfig = allowed ? {
|
|
766
|
+
default: registry.default,
|
|
767
|
+
strategies: Object.fromEntries(Object.entries(registry.strategies).map(([name, strategy]) => [name, guardStrategy(strategy, permits)]))
|
|
768
|
+
} : registry;
|
|
468
769
|
const deps = {
|
|
469
|
-
start: (schemaId, context, o) =>
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
770
|
+
start: (schemaId, context, o) => {
|
|
771
|
+
if (!permits(schemaId)) throw notAllowed(schemaId);
|
|
772
|
+
return wfApp.start(schemaId, context, {
|
|
773
|
+
input: o?.input,
|
|
774
|
+
eventContext: o?.eventContext ?? current(),
|
|
775
|
+
strategy: o?.strategy
|
|
776
|
+
});
|
|
777
|
+
},
|
|
778
|
+
resume: (state, o) => {
|
|
779
|
+
if (!permits(state.schemaId)) throw notAllowed(state.schemaId);
|
|
780
|
+
return wfApp.resume(state, {
|
|
781
|
+
input: o?.input,
|
|
782
|
+
eventContext: o?.eventContext ?? current(),
|
|
783
|
+
strategy: o?.strategy
|
|
784
|
+
});
|
|
785
|
+
}
|
|
479
786
|
};
|
|
787
|
+
reservePendingInviteLink();
|
|
480
788
|
return handleAsOutletRequest({
|
|
481
|
-
|
|
482
|
-
state: this.stateRegistry(),
|
|
789
|
+
state: stateConfig,
|
|
483
790
|
outlets: this.outlets,
|
|
484
791
|
token: opts.token ?? this.token
|
|
485
792
|
}, deps);
|
|
@@ -751,6 +1058,78 @@ let OAuthRuntime = class OAuthRuntime {
|
|
|
751
1058
|
};
|
|
752
1059
|
OAuthRuntime = __decorate([Injectable(), __decorateMetadata("design:paramtypes", [typeof OAuthProviderRegistry === "undefined" ? Object : OAuthProviderRegistry, typeof FederatedLoginService === "undefined" ? Object : FederatedLoginService])], OAuthRuntime);
|
|
753
1060
|
//#endregion
|
|
1061
|
+
//#region src/workflow/auth-messages.ts
|
|
1062
|
+
/**
|
|
1063
|
+
* Code-keyed catalogue of every user-facing text `AuthWorkflow` produces —
|
|
1064
|
+
* form errors, banners, finish envelopes and button labels. Templates are
|
|
1065
|
+
* English; `{name}` placeholders are filled from the message params.
|
|
1066
|
+
*
|
|
1067
|
+
* Override per app with `AuthWorkflowOpts.messages` (a partial map, or a
|
|
1068
|
+
* function that receives the code and params and returns the text — e.g. a
|
|
1069
|
+
* lookup in your own i18n library), or override `AuthWorkflow.msg()`.
|
|
1070
|
+
*/
|
|
1071
|
+
const AOOTH_MESSAGES = {
|
|
1072
|
+
INVALID_CREDENTIALS: "Invalid credentials",
|
|
1073
|
+
ACCOUNT_LOCKED: "Account locked, please try again later",
|
|
1074
|
+
INVALID_PASSWORD: "Invalid password",
|
|
1075
|
+
INCORRECT_PASSWORD: "Incorrect password",
|
|
1076
|
+
SESSION_LIMIT_REACHED: "Session limit reached",
|
|
1077
|
+
INVALID_CODE: "Invalid code",
|
|
1078
|
+
/** Params: `seconds`. */
|
|
1079
|
+
RESEND_WAIT: "Please wait {seconds}s before requesting a new code.",
|
|
1080
|
+
/** Params: `seconds`. */
|
|
1081
|
+
RESEND_WAIT_ANOTHER: "Please wait {seconds}s before requesting another code",
|
|
1082
|
+
/** Params: `seconds`, `channel` (`SMS` / `email`). */
|
|
1083
|
+
RESEND_WAIT_CHANNEL: "Please wait {seconds}s before requesting another {channel} code",
|
|
1084
|
+
TOTP_RESEND_NOT_APPLICABLE: "Resend is not applicable for TOTP",
|
|
1085
|
+
UNKNOWN_MFA_METHOD: "Unknown MFA method",
|
|
1086
|
+
UNKNOWN_METHOD: "Unknown method",
|
|
1087
|
+
METHOD_UNAVAILABLE: "That method isn't available",
|
|
1088
|
+
METHOD_NOT_CHANGEABLE: "That method can't be changed here.",
|
|
1089
|
+
KEEP_ONE_MFA_METHOD: "You must keep at least one two-factor method.",
|
|
1090
|
+
CHOOSE_OPTION: "Choose an option",
|
|
1091
|
+
ALL_MFA_METHODS_SET_UP: "You've already set up every available authentication method.",
|
|
1092
|
+
NO_MFA_CHANGES: "No changes were made to your two-factor methods.",
|
|
1093
|
+
PASSWORDS_DO_NOT_MATCH: "Passwords do not match",
|
|
1094
|
+
PASSWORD_CHANGE_TOO_RECENT: "You changed your password too recently. Please try again later.",
|
|
1095
|
+
PASSWORD_CHANGED: "Your password has been changed.",
|
|
1096
|
+
PASSWORD_UPDATED_REDIRECTING: "Password updated. Redirecting to sign-in…",
|
|
1097
|
+
PASSWORD_UPDATED_STILL_LOCKED: "Password updated, but your account is still locked. Contact an administrator to regain access.",
|
|
1098
|
+
RECOVERY_INSTRUCTIONS_SENT: "If an account exists, you will receive instructions.",
|
|
1099
|
+
SIGNUP_DISABLED: "Self-signup is currently disabled.",
|
|
1100
|
+
ALREADY_HAVE_ACCOUNT: "You already have an account. Please sign in.",
|
|
1101
|
+
ACCOUNT_LINKED: "Account linked.",
|
|
1102
|
+
INVALID_ROLE: "Invalid role",
|
|
1103
|
+
INVITE_ALREADY_PENDING: "Invite already pending",
|
|
1104
|
+
USER_ALREADY_EXISTS: "User already exists",
|
|
1105
|
+
DUPLICATE_INVITE_REJECTED: "Duplicate invite rejected",
|
|
1106
|
+
INVITE_CANCELLED: "This invite has been cancelled",
|
|
1107
|
+
INVITE_REPLACED: "This invite was replaced by a newer one",
|
|
1108
|
+
INVITE_ALREADY_ACCEPTED: "This invite was already accepted.",
|
|
1109
|
+
CHOOSE_USERNAME_TAKEN: "This username is taken",
|
|
1110
|
+
USERNAME_NOT_ALLOWED: "This username is not allowed",
|
|
1111
|
+
AUTHZ_EXPIRED: "Authorization request expired. Please try again.",
|
|
1112
|
+
AUTHZ_BROWSER_MISMATCH: "This authorization could not be verified for your browser. Please start again.",
|
|
1113
|
+
AUTHZ_FAILED: "Authorization could not be completed. Please start again.",
|
|
1114
|
+
GO_TO_SIGN_IN: "Go to sign-in",
|
|
1115
|
+
BACK_TO_SIGN_IN: "Back to sign-in",
|
|
1116
|
+
REQUEST_NEW_INVITE: "Request a new invite",
|
|
1117
|
+
BACK: "Back",
|
|
1118
|
+
GO_NOW: "Go now"
|
|
1119
|
+
};
|
|
1120
|
+
/** Fill `{name}` placeholders from `params`; unknown placeholders are kept. */
|
|
1121
|
+
function renderAoothMessage(template, params = {}) {
|
|
1122
|
+
return template.replace(/\{(\w+)\}/g, (whole, name) => Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : whole);
|
|
1123
|
+
}
|
|
1124
|
+
/** Resolve `code` through `messages` (when given), falling back to the English template. */
|
|
1125
|
+
function resolveAoothMessage(code, params = {}, messages) {
|
|
1126
|
+
if (typeof messages === "function") {
|
|
1127
|
+
const text = messages(code, params);
|
|
1128
|
+
if (text !== void 0) return text;
|
|
1129
|
+
} else if (messages?.[code] !== void 0) return renderAoothMessage(messages[code], params);
|
|
1130
|
+
return renderAoothMessage(AOOTH_MESSAGES[code], params);
|
|
1131
|
+
}
|
|
1132
|
+
//#endregion
|
|
754
1133
|
//#region src/workflow/auth-workflow.schemas.ts
|
|
755
1134
|
/**
|
|
756
1135
|
* Canonical OTP send-then-check pair. Used by:
|
|
@@ -971,6 +1350,7 @@ const DEFAULT_FORMS = {
|
|
|
971
1350
|
pincode: PincodeForm,
|
|
972
1351
|
setPassword: SetPasswordForm,
|
|
973
1352
|
changePassword: ChangePasswordForm,
|
|
1353
|
+
inviteChooseUsername: InviteChooseUsernameForm,
|
|
974
1354
|
proveControl: ProveControlForm,
|
|
975
1355
|
proveControlOtp: ProveControlOtpForm,
|
|
976
1356
|
termsBump: TermsBumpForm,
|
|
@@ -979,6 +1359,28 @@ const DEFAULT_FORMS = {
|
|
|
979
1359
|
signup: SignupForm,
|
|
980
1360
|
authzConsent: AuthorizeConsentForm
|
|
981
1361
|
};
|
|
1362
|
+
/**
|
|
1363
|
+
* Process-wide warn-once latches (module level: `AuthWorkflow` may be
|
|
1364
|
+
* event-scoped, and a per-instance flag would warn on every request).
|
|
1365
|
+
*/
|
|
1366
|
+
const warnedOnce = {
|
|
1367
|
+
openInviteWhitelist: false,
|
|
1368
|
+
crossIssuerReuse: false
|
|
1369
|
+
};
|
|
1370
|
+
/** Sliding lifetime of a shadow failure counter (and of a shadow "permanent" lock). */
|
|
1371
|
+
const SHADOW_TTL_MS = 720 * 60 * 6e4;
|
|
1372
|
+
/** Key prefix of an active shadow lock (kept longest by the default store). */
|
|
1373
|
+
const SHADOW_LOCK_PREFIX = "shadow-lock:";
|
|
1374
|
+
/** Cap of the default (process-wide, in-memory) shadow-lockout store. */
|
|
1375
|
+
const SHADOW_STORE_MAX_ENTRIES = 5e4;
|
|
1376
|
+
let sharedShadowStore;
|
|
1377
|
+
function defaultShadowStore() {
|
|
1378
|
+
sharedShadowStore ??= new RateLimitStoreMemory$1({
|
|
1379
|
+
maxEntries: SHADOW_STORE_MAX_ENTRIES,
|
|
1380
|
+
evictLast: (key) => key.startsWith(SHADOW_LOCK_PREFIX)
|
|
1381
|
+
});
|
|
1382
|
+
return sharedShadowStore;
|
|
1383
|
+
}
|
|
982
1384
|
function mergeAuthWorkflowOpts(opts) {
|
|
983
1385
|
const deviceTrust = {
|
|
984
1386
|
cookieName: "aooth_trusted_device",
|
|
@@ -991,6 +1393,12 @@ function mergeAuthWorkflowOpts(opts) {
|
|
|
991
1393
|
autoLoginOnRecover: opts.autoLoginOnRecover ?? false,
|
|
992
1394
|
invitableRoles: opts.invitableRoles ?? [],
|
|
993
1395
|
allowAnyInviteRole: opts.allowAnyInviteRole ?? false,
|
|
1396
|
+
inviteDelivery: opts.inviteDelivery ?? "outlet-email",
|
|
1397
|
+
...opts.inviteLinkUrl && { inviteLinkUrl: opts.inviteLinkUrl },
|
|
1398
|
+
inviteUsername: opts.inviteUsername ?? "email",
|
|
1399
|
+
...opts.messages !== void 0 && { messages: opts.messages },
|
|
1400
|
+
lockoutDisclosure: opts.lockoutDisclosure ?? "uniform",
|
|
1401
|
+
lockoutShadowStore: opts.lockoutShadowStore ?? defaultShadowStore(),
|
|
994
1402
|
mfa: {
|
|
995
1403
|
pincodeLength: opts.mfa?.pincodeLength ?? 6,
|
|
996
1404
|
pincodeTtlMs: opts.mfa?.pincodeTtlMs ?? 300 * 1e3,
|
|
@@ -1108,15 +1516,16 @@ function parseInviteRoles(input) {
|
|
|
1108
1516
|
*/
|
|
1109
1517
|
function buildInviteAlreadyAcceptedEnvelope(opts) {
|
|
1110
1518
|
const altUrl = opts.alreadyAcceptedRedirectUrl;
|
|
1519
|
+
const msg = (code) => resolveAoothMessage(code, {}, opts.messages);
|
|
1111
1520
|
return {
|
|
1112
1521
|
message: {
|
|
1113
1522
|
level: "info",
|
|
1114
|
-
text: "
|
|
1523
|
+
text: msg("INVITE_ALREADY_ACCEPTED")
|
|
1115
1524
|
},
|
|
1116
1525
|
next: {
|
|
1117
1526
|
trigger: "manual",
|
|
1118
1527
|
primary: {
|
|
1119
|
-
label: "
|
|
1528
|
+
label: msg("GO_TO_SIGN_IN"),
|
|
1120
1529
|
action: {
|
|
1121
1530
|
type: "redirect",
|
|
1122
1531
|
target: opts.loginUrl,
|
|
@@ -1124,7 +1533,7 @@ function buildInviteAlreadyAcceptedEnvelope(opts) {
|
|
|
1124
1533
|
}
|
|
1125
1534
|
},
|
|
1126
1535
|
...altUrl && { options: [{
|
|
1127
|
-
label: "
|
|
1536
|
+
label: msg("REQUEST_NEW_INVITE"),
|
|
1128
1537
|
action: {
|
|
1129
1538
|
type: "redirect",
|
|
1130
1539
|
target: altUrl,
|
|
@@ -1148,6 +1557,12 @@ const ALT_HANDLED = Symbol("ALT_HANDLED");
|
|
|
1148
1557
|
* re-decorating the step in a subclass.
|
|
1149
1558
|
*/
|
|
1150
1559
|
const INVITE_LINK_TTL_MS = 10080 * 60 * 1e3;
|
|
1560
|
+
/** One canonical form of a chosen username: Unicode NFKC, surrounding whitespace trimmed. */
|
|
1561
|
+
function normalizeUsername(raw) {
|
|
1562
|
+
return String(raw).normalize("NFKC").trim();
|
|
1563
|
+
}
|
|
1564
|
+
/** Loose email shape — `account.verifiedEmail` is only recorded for a value that looks like one. */
|
|
1565
|
+
const EMAIL_SHAPE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
|
|
1151
1566
|
/**
|
|
1152
1567
|
* Read a single field from the raw wf input envelope without validating
|
|
1153
1568
|
* against any form schema. Used by alt-action handlers that carry a payload
|
|
@@ -1205,12 +1620,21 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
1205
1620
|
users;
|
|
1206
1621
|
auth;
|
|
1207
1622
|
consentStore;
|
|
1208
|
-
/**
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1623
|
+
/** The invite context every invite hook receives: issuer, app context, extra form fields. */
|
|
1624
|
+
inviteHookInput(ctx) {
|
|
1625
|
+
const admin = ctx.admin;
|
|
1626
|
+
return {
|
|
1627
|
+
...admin?.invitedBy && { invitedBy: admin.invitedBy },
|
|
1628
|
+
...admin?.app && { app: admin.app },
|
|
1629
|
+
...admin?.form && { form: admin.form }
|
|
1630
|
+
};
|
|
1631
|
+
}
|
|
1632
|
+
/** Warn once per process when a `'reuse'` re-invite crosses issuers. */
|
|
1633
|
+
warnCrossIssuerReuse() {
|
|
1634
|
+
if (warnedOnce.crossIssuerReuse) return;
|
|
1635
|
+
warnedOnce.crossIssuerReuse = true;
|
|
1636
|
+
useLogger("aooth:auth", current()).warn("A re-invite ('reuse') took over a pending invite issued by another user — its roles and extras were replaced and the earlier link no longer works. Override `duplicateInviteCheck()` (it receives `invitedBy`, `app` and `pending`) to refuse it.");
|
|
1637
|
+
}
|
|
1214
1638
|
constructor(opts, users, auth, consentStore) {
|
|
1215
1639
|
this.opts = mergeAuthWorkflowOpts(opts);
|
|
1216
1640
|
this.users = users;
|
|
@@ -1218,6 +1642,23 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
1218
1642
|
this.consentStore = consentStore;
|
|
1219
1643
|
}
|
|
1220
1644
|
/**
|
|
1645
|
+
* Resolve a user-facing text by code (`AOOTH_MESSAGES`) through
|
|
1646
|
+
* `opts.messages`. Every form error, banner, finish message and button label
|
|
1647
|
+
* the workflow produces goes through here — override for full control
|
|
1648
|
+
* (e.g. to call your i18n library with the request's locale).
|
|
1649
|
+
*/
|
|
1650
|
+
msg(code, params) {
|
|
1651
|
+
return resolveAoothMessage(code, params, this.opts.messages);
|
|
1652
|
+
}
|
|
1653
|
+
/** An `HttpError` whose body carries the message `code` next to its (resolved) text. */
|
|
1654
|
+
httpError(status, code) {
|
|
1655
|
+
return new HttpError$1(status, {
|
|
1656
|
+
message: this.msg(code),
|
|
1657
|
+
statusCode: status,
|
|
1658
|
+
code
|
|
1659
|
+
});
|
|
1660
|
+
}
|
|
1661
|
+
/**
|
|
1221
1662
|
* Unified outbound dispatch hook for direct synchronous deliveries
|
|
1222
1663
|
* (MFA / recovery / enrollment pincodes, new-device notices). NOT used for
|
|
1223
1664
|
* resume-token flows — the invite magic link is emitted via the wf engine's
|
|
@@ -1362,6 +1803,16 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
1362
1803
|
return [];
|
|
1363
1804
|
}
|
|
1364
1805
|
/**
|
|
1806
|
+
* App context of an invite, resolved once when the issue phase starts
|
|
1807
|
+
* (`init-invite-admin`) from the trigger's START input (`{ wfid, input: {
|
|
1808
|
+
* formData } }` — the `startFormData` argument) and the session. Return
|
|
1809
|
+
* e.g. `{ tenantId }`; the value is kept server-side as `ctx.admin.app` and
|
|
1810
|
+
* handed to `prepareUser`, `inferAdminRoles` and `duplicateInviteCheck`.
|
|
1811
|
+
* Throw an `HttpError` to refuse the invite (e.g. the issuer may not invite
|
|
1812
|
+
* into that tenant). Default: `undefined` (no app context).
|
|
1813
|
+
*/
|
|
1814
|
+
resolveInviteContext(_ctx, _startFormData) {}
|
|
1815
|
+
/**
|
|
1365
1816
|
* Override the structural duplicate rule for `admin-form`. Default: a row
|
|
1366
1817
|
* still parked on `account.pendingInvitation` → `'reuse'` (re-invite:
|
|
1367
1818
|
* `create-user` refreshes the existing record in place and `send-email`
|
|
@@ -1371,7 +1822,11 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
1371
1822
|
* Multi-tenant apps that allow re-inviting the same email into a different
|
|
1372
1823
|
* tenant override to `'allow'`. Apps that want the strict legacy behavior
|
|
1373
1824
|
* ("Invite already pending" error on a duplicate invite of a pending user)
|
|
1374
|
-
* return `'reject'` for pending rows.
|
|
1825
|
+
* return `'reject'` for pending rows. Compare `invitedBy` / `app` with
|
|
1826
|
+
* `pending` and `existingUser` to refuse taking over another issuer's (or
|
|
1827
|
+
* tenant's) pending invite. On `'reuse'` the row's roles and extras are
|
|
1828
|
+
* REPLACED by this invite's, and every link issued before is superseded
|
|
1829
|
+
* (answers 410 "replaced").
|
|
1375
1830
|
*/
|
|
1376
1831
|
duplicateInviteCheck(input) {
|
|
1377
1832
|
if (input.existingUser?.account?.pendingInvitation) return "reuse";
|
|
@@ -2063,6 +2518,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
2063
2518
|
"policies"
|
|
2064
2519
|
]);
|
|
2065
2520
|
if (sub) pub.password = sub;
|
|
2521
|
+
const mismatch = this.msg("PASSWORDS_DO_NOT_MATCH");
|
|
2522
|
+
if (mismatch !== AOOTH_MESSAGES.PASSWORDS_DO_NOT_MATCH) pub.messages = { PASSWORDS_DO_NOT_MATCH: mismatch };
|
|
2066
2523
|
}
|
|
2067
2524
|
if (ctx.admin) {
|
|
2068
2525
|
const sub = pickDefined(ctx.admin, ["availableRoles"]);
|
|
@@ -2469,14 +2926,18 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
2469
2926
|
await this.seedChannelState(ctx, user);
|
|
2470
2927
|
return true;
|
|
2471
2928
|
}
|
|
2472
|
-
initInviteAdmin(ctx) {
|
|
2929
|
+
async initInviteAdmin(ctx) {
|
|
2473
2930
|
ctx.autoLogin = this.opts.autoLoginOnInvite;
|
|
2931
|
+
const startFormData = useWfState().input()?.formData;
|
|
2932
|
+
const app = await this.resolveInviteContext(ctx, startFormData);
|
|
2933
|
+
if (app !== void 0) (ctx.admin ??= {}).app = app;
|
|
2474
2934
|
}
|
|
2475
2935
|
initInviteAccept(ctx) {
|
|
2476
2936
|
ctx.isFirstLogin = true;
|
|
2477
2937
|
ctx.newPasswordRequired = true;
|
|
2478
2938
|
ctx.autoLogin = this.opts.autoLoginOnInvite;
|
|
2479
2939
|
(ctx.password ??= {}).changeReason = "initial";
|
|
2940
|
+
if (this.opts.inviteUsername === "choose") (ctx.accept ??= {}).chooseUsername = true;
|
|
2480
2941
|
}
|
|
2481
2942
|
initRecovery(ctx) {
|
|
2482
2943
|
ctx.autoLogin = this.opts.autoLoginOnRecover;
|
|
@@ -2587,13 +3048,48 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
2587
3048
|
if (!ctx.notice?.email) await this.seedCorrespondenceEmail(ctx, result.user);
|
|
2588
3049
|
} catch (err) {
|
|
2589
3050
|
if (err instanceof UserAuthError) {
|
|
2590
|
-
|
|
2591
|
-
throw this.throwPublic(ctx, wf, { formMessage: "
|
|
3051
|
+
const locked = await this.failedLoginReadsLocked(ctx, err, input.username);
|
|
3052
|
+
throw this.throwPublic(ctx, wf, { formMessage: this.msg(locked ? "ACCOUNT_LOCKED" : "INVALID_CREDENTIALS") });
|
|
2592
3053
|
}
|
|
2593
3054
|
throw err;
|
|
2594
3055
|
}
|
|
2595
3056
|
}
|
|
2596
3057
|
/**
|
|
3058
|
+
* Whether a failed password sign-in answers "Account locked" — see
|
|
3059
|
+
* `AuthWorkflowOpts.lockoutDisclosure`. Under `'uniform'` an unknown or
|
|
3060
|
+
* inactive handle keeps a shadow failure counter in `lockoutShadowStore`
|
|
3061
|
+
* that mirrors a real account exactly: every failure counts (the counter is
|
|
3062
|
+
* not reset when it trips — like `failedLoginAttempts`), a lock starts when
|
|
3063
|
+
* `failures >= threshold` and none is active, the tripping attempt still
|
|
3064
|
+
* reads "Invalid credentials", and a permanent lock stays on while probed.
|
|
3065
|
+
* Keys are a hash of the normalised handle (bounded size); the counter
|
|
3066
|
+
* slides for 30 days of inactivity.
|
|
3067
|
+
*/
|
|
3068
|
+
async failedLoginReadsLocked(ctx, err, handle) {
|
|
3069
|
+
const mode = this.opts.lockoutDisclosure;
|
|
3070
|
+
if (mode === "generic") return false;
|
|
3071
|
+
if (err.type === "LOCKED") return true;
|
|
3072
|
+
if (mode !== "uniform" || err.type !== "NOT_FOUND" && err.type !== "INACTIVE") return false;
|
|
3073
|
+
const { threshold, duration } = {
|
|
3074
|
+
...this.users.getConfig().lockout,
|
|
3075
|
+
...this.lockoutOverride(ctx)
|
|
3076
|
+
};
|
|
3077
|
+
if (threshold <= 0) return false;
|
|
3078
|
+
const store = this.opts.lockoutShadowStore;
|
|
3079
|
+
const id = createHash("sha256").update(handle.trim().toLowerCase()).digest("base64url");
|
|
3080
|
+
const lockKey = `${SHADOW_LOCK_PREFIX}${id}`;
|
|
3081
|
+
if (store.get && await store.get(lockKey) > 0) {
|
|
3082
|
+
if (duration <= 0) await store.expire?.(lockKey, SHADOW_TTL_MS);
|
|
3083
|
+
return true;
|
|
3084
|
+
}
|
|
3085
|
+
const failKey = `shadow-fail:${id}`;
|
|
3086
|
+
const failures = await store.hit(failKey, SHADOW_TTL_MS);
|
|
3087
|
+
if (failures > 1) await store.expire?.(failKey, SHADOW_TTL_MS);
|
|
3088
|
+
if (!store.get) return failures > threshold;
|
|
3089
|
+
if (failures >= threshold) await store.hit(lockKey, duration > 0 ? duration : SHADOW_TTL_MS);
|
|
3090
|
+
return false;
|
|
3091
|
+
}
|
|
3092
|
+
/**
|
|
2597
3093
|
* Route a credentials alt-action click (forgotPassword / signup / magicLink
|
|
2598
3094
|
* / sso-<id>) to a `finishWf` redirect envelope. Returns `ALT_HANDLED` when
|
|
2599
3095
|
* the caller should short-circuit without running form validation.
|
|
@@ -2684,7 +3180,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
2684
3180
|
data: { sent: true },
|
|
2685
3181
|
message: {
|
|
2686
3182
|
level: "info",
|
|
2687
|
-
text:
|
|
3183
|
+
text: this.msg("RECOVERY_INSTRUCTIONS_SENT")
|
|
2688
3184
|
}
|
|
2689
3185
|
});
|
|
2690
3186
|
}
|
|
@@ -2866,8 +3362,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
2866
3362
|
async prepareAvailableRoles(ctx) {
|
|
2867
3363
|
const roles = await this.getAvailableRoles();
|
|
2868
3364
|
if (roles) (ctx.admin ??= {}).availableRoles = roles;
|
|
2869
|
-
else if (!
|
|
2870
|
-
|
|
3365
|
+
else if (!warnedOnce.openInviteWhitelist && this.inviteWhitelistIsOpen()) {
|
|
3366
|
+
warnedOnce.openInviteWhitelist = true;
|
|
2871
3367
|
useLogger("aooth:auth", current()).warn("Invite role whitelist is OFF — the admin invite form can assign ANY role, including privileged ones. Set `invitableRoles` (intersected with the inviter's ARBAC grants), override `getAvailableRoles()`, or set `allowAnyInviteRole: true` to acknowledge the open default.");
|
|
2872
3368
|
}
|
|
2873
3369
|
}
|
|
@@ -2926,24 +3422,32 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
2926
3422
|
*/
|
|
2927
3423
|
async adminForm(ctx) {
|
|
2928
3424
|
const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.invite);
|
|
2929
|
-
const
|
|
2930
|
-
const
|
|
2931
|
-
const parsed = this.effectiveInviteRoles(ctx, input.roles);
|
|
3425
|
+
const { email, roles, ...extra } = wf.resolveInput();
|
|
3426
|
+
const parsed = this.effectiveInviteRoles(ctx, roles);
|
|
2932
3427
|
if (Array.isArray(ctx.admin?.availableRoles)) {
|
|
2933
3428
|
const allowed = new Set(ctx.admin.availableRoles);
|
|
2934
|
-
if (parsed.find((r) => !allowed.has(r)) !== void 0) throw this.throwPublic(ctx, wf, { errors: { roles: "
|
|
3429
|
+
if (parsed.find((r) => !allowed.has(r)) !== void 0) throw this.throwPublic(ctx, wf, { errors: { roles: this.msg("INVALID_ROLE") } });
|
|
2935
3430
|
}
|
|
3431
|
+
if (Object.keys(extra).length > 0) (ctx.admin ??= {}).form = extra;
|
|
2936
3432
|
const existing = await this.users.findByHandle(email);
|
|
3433
|
+
const invitedBy = useAuth().getAuthContext()?.userId;
|
|
3434
|
+
const pendingIssuer = existing?.account?.pendingInvitation ? existing.account.invitedBy : void 0;
|
|
3435
|
+
if (invitedBy) (ctx.admin ??= {}).invitedBy = invitedBy;
|
|
2937
3436
|
const action = await this.duplicateInviteCheck({
|
|
2938
3437
|
email,
|
|
2939
|
-
existingUser: existing
|
|
3438
|
+
existingUser: existing,
|
|
3439
|
+
...this.inviteHookInput(ctx),
|
|
3440
|
+
...existing?.account?.pendingInvitation && { pending: pendingIssuer === void 0 ? {} : { invitedBy: pendingIssuer } }
|
|
2940
3441
|
});
|
|
2941
3442
|
if (action === "reject") {
|
|
2942
|
-
if (existing?.account?.pendingInvitation) throw this.throwPublic(ctx, wf, { errors: { email: "
|
|
2943
|
-
if (existing) throw this.throwPublic(ctx, wf, { errors: { email: "
|
|
2944
|
-
throw this.throwPublic(ctx, wf, { errors: { email: "
|
|
3443
|
+
if (existing?.account?.pendingInvitation) throw this.throwPublic(ctx, wf, { errors: { email: this.msg("INVITE_ALREADY_PENDING") } });
|
|
3444
|
+
if (existing) throw this.throwPublic(ctx, wf, { errors: { email: this.msg("USER_ALREADY_EXISTS") } });
|
|
3445
|
+
throw this.throwPublic(ctx, wf, { errors: { email: this.msg("DUPLICATE_INVITE_REJECTED") } });
|
|
3446
|
+
}
|
|
3447
|
+
if (action === "reuse") {
|
|
3448
|
+
(ctx.admin ??= {}).reuseExisting = true;
|
|
3449
|
+
if (pendingIssuer !== void 0 && invitedBy !== void 0 && pendingIssuer !== invitedBy) this.warnCrossIssuerReuse();
|
|
2945
3450
|
}
|
|
2946
|
-
if (action === "reuse") (ctx.admin ??= {}).reuseExisting = true;
|
|
2947
3451
|
ctx.email = email;
|
|
2948
3452
|
if (parsed.length > 0) (ctx.admin ??= {}).roles = parsed;
|
|
2949
3453
|
}
|
|
@@ -2953,7 +3457,10 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
2953
3457
|
*/
|
|
2954
3458
|
async inferRoles(ctx) {
|
|
2955
3459
|
if (!ctx.email) return void 0;
|
|
2956
|
-
const inferred = await this.inferAdminRoles({
|
|
3460
|
+
const inferred = await this.inferAdminRoles({
|
|
3461
|
+
email: ctx.email,
|
|
3462
|
+
...this.inviteHookInput(ctx)
|
|
3463
|
+
});
|
|
2957
3464
|
if (inferred.length === 0) return void 0;
|
|
2958
3465
|
const admin = ctx.admin ??= {};
|
|
2959
3466
|
const merged = /* @__PURE__ */ new Set([...admin.roles ?? [], ...inferred]);
|
|
@@ -2966,16 +3473,26 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
2966
3473
|
*/
|
|
2967
3474
|
async buildUserExtras(ctx) {
|
|
2968
3475
|
if (!ctx.email) throw new HttpError$1(500, "Workflow state corrupted: missing email");
|
|
2969
|
-
const invitedBy = useAuth().getAuthContext()?.userId;
|
|
3476
|
+
const invitedBy = ctx.admin?.invitedBy ?? useAuth().getAuthContext()?.userId;
|
|
3477
|
+
if (invitedBy) (ctx.admin ??= {}).invitedBy = invitedBy;
|
|
2970
3478
|
const preparedInput = {
|
|
2971
3479
|
email: ctx.email,
|
|
2972
3480
|
roles: ctx.admin?.roles ?? [],
|
|
2973
|
-
...
|
|
3481
|
+
...this.inviteHookInput(ctx)
|
|
2974
3482
|
};
|
|
2975
|
-
const extras = await this.prepareUser(preparedInput);
|
|
3483
|
+
const extras = await this.prepareUser(preparedInput) ?? {};
|
|
2976
3484
|
(ctx.admin ??= {}).userExtras = extras;
|
|
2977
3485
|
}
|
|
2978
3486
|
/**
|
|
3487
|
+
* Invariant of the invite issue phase: once the admin form is accepted, the
|
|
3488
|
+
* pending user must exist before the link is sent. An issue phase that ends
|
|
3489
|
+
* without one (a broken override, a store that silently dropped the row) is
|
|
3490
|
+
* a server error — never a bare `{ finished: true }`.
|
|
3491
|
+
*/
|
|
3492
|
+
assertInviteCreated(ctx) {
|
|
3493
|
+
if (ctx.email && !ctx.subject) throw new HttpError$1(500, "Invite issue failed: the invited user was not created");
|
|
3494
|
+
}
|
|
3495
|
+
/**
|
|
2979
3496
|
* Create the user row from `ctx.admin.userExtras` (plus the admin-supplied
|
|
2980
3497
|
* `ctx.admin.roles`), then stamp `pendingInvitation = true` via a follow-up
|
|
2981
3498
|
* deep-merge update so `createUser`-applied account defaults survive.
|
|
@@ -2995,18 +3512,25 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
2995
3512
|
*/
|
|
2996
3513
|
async createUser(ctx) {
|
|
2997
3514
|
if (!ctx.email) throw new HttpError$1(500, "Workflow state corrupted: missing email");
|
|
2998
|
-
const
|
|
3515
|
+
const admin = ctx.admin ??= {};
|
|
3516
|
+
const adminRoles = admin.roles;
|
|
2999
3517
|
const fields = {
|
|
3000
|
-
...
|
|
3518
|
+
...admin.userExtras,
|
|
3001
3519
|
...adminRoles && adminRoles.length > 0 && { roles: adminRoles }
|
|
3002
3520
|
};
|
|
3003
|
-
|
|
3521
|
+
admin.inviteNonce = randomBytes(16).toString("base64url");
|
|
3522
|
+
const pendingAccount = {
|
|
3523
|
+
pendingInvitation: true,
|
|
3524
|
+
inviteNonce: admin.inviteNonce,
|
|
3525
|
+
...admin.invitedBy && { invitedBy: admin.invitedBy }
|
|
3526
|
+
};
|
|
3527
|
+
if (admin.reuseExisting) {
|
|
3004
3528
|
const existing = await this.users.findByHandle(ctx.email);
|
|
3005
3529
|
if (existing) {
|
|
3006
|
-
if (!existing.account?.pendingInvitation) throw
|
|
3530
|
+
if (!existing.account?.pendingInvitation) throw this.httpError(409, "USER_ALREADY_EXISTS");
|
|
3007
3531
|
await this.users.update(existing.id, {
|
|
3008
3532
|
...fields,
|
|
3009
|
-
account:
|
|
3533
|
+
account: pendingAccount
|
|
3010
3534
|
});
|
|
3011
3535
|
ctx.subject = existing.id;
|
|
3012
3536
|
return;
|
|
@@ -3016,10 +3540,10 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3016
3540
|
try {
|
|
3017
3541
|
created = await this.users.createUser(ctx.email, void 0, fields);
|
|
3018
3542
|
} catch (err) {
|
|
3019
|
-
if (err instanceof UserAuthError && err.type === "ALREADY_EXISTS") throw
|
|
3543
|
+
if (err instanceof UserAuthError && err.type === "ALREADY_EXISTS") throw this.httpError(409, "USER_ALREADY_EXISTS");
|
|
3020
3544
|
throw err;
|
|
3021
3545
|
}
|
|
3022
|
-
await this.users.update(created.id, { account:
|
|
3546
|
+
await this.users.update(created.id, { account: pendingAccount });
|
|
3023
3547
|
ctx.subject = created.id;
|
|
3024
3548
|
}
|
|
3025
3549
|
/**
|
|
@@ -3045,12 +3569,40 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3045
3569
|
const admin = ctx.admin ??= {};
|
|
3046
3570
|
if (admin.emailDispatched) return void 0;
|
|
3047
3571
|
admin.emailDispatched = true;
|
|
3572
|
+
const mode = this.opts.inviteDelivery;
|
|
3573
|
+
admin.inviteDelivery = mode;
|
|
3048
3574
|
swapStrategy("store");
|
|
3049
|
-
|
|
3050
|
-
|
|
3575
|
+
const email = ctx.email;
|
|
3576
|
+
if (mode === "outlet-email") return outletEmail(email, "invite.magicLink", {
|
|
3577
|
+
username: email,
|
|
3051
3578
|
...ctx.subject && { userId: ctx.subject },
|
|
3052
3579
|
...admin.roles && { roles: admin.roles }
|
|
3053
3580
|
});
|
|
3581
|
+
const buildUrl = this.opts.inviteLinkUrl;
|
|
3582
|
+
if (!buildUrl) throw new HttpError$1(500, `inviteDelivery '${mode}' requires AuthWorkflowOpts.inviteLinkUrl`);
|
|
3583
|
+
const userId = ctx.subject;
|
|
3584
|
+
setPendingInviteLink(async (token) => {
|
|
3585
|
+
const url = buildUrl(token, { ...userId && { userId } });
|
|
3586
|
+
if (mode === "return-link") return {
|
|
3587
|
+
outlet: "invite",
|
|
3588
|
+
data: {
|
|
3589
|
+
inviteLink: url,
|
|
3590
|
+
...userId && { userId }
|
|
3591
|
+
}
|
|
3592
|
+
};
|
|
3593
|
+
await this.deliver({
|
|
3594
|
+
kind: "invite-link",
|
|
3595
|
+
channel: "email",
|
|
3596
|
+
recipient: email,
|
|
3597
|
+
url,
|
|
3598
|
+
expiresInMs: INVITE_LINK_TTL_MS
|
|
3599
|
+
});
|
|
3600
|
+
return {
|
|
3601
|
+
sent: true,
|
|
3602
|
+
outlet: "invite"
|
|
3603
|
+
};
|
|
3604
|
+
});
|
|
3605
|
+
return outlet(INVITE_OUTLET, { target: email });
|
|
3054
3606
|
}
|
|
3055
3607
|
/**
|
|
3056
3608
|
* Check whether the invite was already accepted. Sets
|
|
@@ -3058,10 +3610,57 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3058
3610
|
* cleared.
|
|
3059
3611
|
*/
|
|
3060
3612
|
async checkPendingInvitation(ctx) {
|
|
3061
|
-
if (!ctx.
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3613
|
+
if (!(await this.currentInviteRow(ctx)).account?.pendingInvitation) (ctx.accept ??= {}).alreadyAccepted = true;
|
|
3614
|
+
}
|
|
3615
|
+
/**
|
|
3616
|
+
* Username policy for `inviteUsername: 'choose'`, applied to the normalised
|
|
3617
|
+
* (NFKC, trimmed) pick. Return a message code to refuse it. Default: at most
|
|
3618
|
+
* 256 characters, no whitespace or control characters, and no `@` unless it
|
|
3619
|
+
* is the invited address itself — a chosen name must not look like someone
|
|
3620
|
+
* else's email handle (sign-in resolves `username` before email columns).
|
|
3621
|
+
*/
|
|
3622
|
+
validateChosenUsername(ctx, username) {
|
|
3623
|
+
if (username.length === 0 || username.length > 256) return "USERNAME_NOT_ALLOWED";
|
|
3624
|
+
if (/[\s\u0000-\u001f\u007f]/.test(username)) return "USERNAME_NOT_ALLOWED";
|
|
3625
|
+
if (username.includes("@") && username.toLowerCase() !== ctx.email?.toLowerCase()) return "USERNAME_NOT_ALLOWED";
|
|
3626
|
+
}
|
|
3627
|
+
/**
|
|
3628
|
+
* The invited account, refusing a cancelled invite (410 `INVITE_CANCELLED`,
|
|
3629
|
+
* the row is gone) or a superseded link (410 `INVITE_REPLACED`, a re-invite
|
|
3630
|
+
* rotated the account's marker away from this run's).
|
|
3631
|
+
*/
|
|
3632
|
+
async currentInviteRow(ctx) {
|
|
3633
|
+
this.requireSubject(ctx);
|
|
3634
|
+
const user = await this.users.findByIdentifier(ctx.subject);
|
|
3635
|
+
if (!user) throw this.httpError(410, "INVITE_CANCELLED");
|
|
3636
|
+
const current = user.account?.inviteNonce;
|
|
3637
|
+
if (current !== void 0 && current !== ctx.admin?.inviteNonce) throw this.httpError(410, "INVITE_REPLACED");
|
|
3638
|
+
return user;
|
|
3639
|
+
}
|
|
3640
|
+
/**
|
|
3641
|
+
* Re-check, right before an invite-accept write, that this run's link is
|
|
3642
|
+
* still the current one and the invite is still pending — a re-invite or a
|
|
3643
|
+
* parallel acceptance may have happened while this run was paused.
|
|
3644
|
+
*/
|
|
3645
|
+
async assertInviteStillOpen(ctx) {
|
|
3646
|
+
if (!(await this.currentInviteRow(ctx)).account?.pendingInvitation) throw this.httpError(410, "INVITE_ALREADY_ACCEPTED");
|
|
3647
|
+
}
|
|
3648
|
+
/**
|
|
3649
|
+
* `inviteUsername: 'choose'` — the invitee picks the username they will
|
|
3650
|
+
* sign in with (the invited email stays the correspondence address). The
|
|
3651
|
+
* pick replaces the account's login handle; a taken one re-pauses.
|
|
3652
|
+
*/
|
|
3653
|
+
async chooseUsername(ctx) {
|
|
3654
|
+
this.requireSubject(ctx);
|
|
3655
|
+
const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.inviteChooseUsername);
|
|
3656
|
+
const username = normalizeUsername(wf.resolveInput().username);
|
|
3657
|
+
await this.assertInviteStillOpen(ctx);
|
|
3658
|
+
const refused = this.validateChosenUsername(ctx, username);
|
|
3659
|
+
if (refused) throw this.throwPublic(ctx, wf, { errors: { username: this.msg(refused) } });
|
|
3660
|
+
const taken = await this.users.findByHandle(username);
|
|
3661
|
+
if (taken && taken.id !== ctx.subject) throw this.throwPublic(ctx, wf, { errors: { username: this.msg("CHOOSE_USERNAME_TAKEN") } });
|
|
3662
|
+
await this.users.update(ctx.subject, { username });
|
|
3663
|
+
(ctx.accept ??= {}).usernameChosen = true;
|
|
3065
3664
|
}
|
|
3066
3665
|
/**
|
|
3067
3666
|
* Emit the "this invite was already accepted" finish envelope and short-
|
|
@@ -3070,7 +3669,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3070
3669
|
idempotentRedirect(ctx) {
|
|
3071
3670
|
finishWf(buildInviteAlreadyAcceptedEnvelope({
|
|
3072
3671
|
loginUrl: ctx.accept.loginUrl,
|
|
3073
|
-
alreadyAcceptedRedirectUrl: ctx.accept.alreadyAcceptedRedirectUrl
|
|
3672
|
+
alreadyAcceptedRedirectUrl: ctx.accept.alreadyAcceptedRedirectUrl,
|
|
3673
|
+
...this.opts.messages !== void 0 && { messages: this.opts.messages }
|
|
3074
3674
|
}));
|
|
3075
3675
|
}
|
|
3076
3676
|
/**
|
|
@@ -3078,12 +3678,17 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3078
3678
|
*/
|
|
3079
3679
|
async unsetPendingInvitation(ctx) {
|
|
3080
3680
|
this.requireSubject(ctx);
|
|
3081
|
-
await this.users.
|
|
3681
|
+
if (!await this.users.acceptInvitation(ctx.subject, ctx.admin?.inviteNonce)) {
|
|
3682
|
+
await this.assertInviteStillOpen(ctx);
|
|
3683
|
+
throw this.httpError(410, "INVITE_ALREADY_ACCEPTED");
|
|
3684
|
+
}
|
|
3082
3685
|
}
|
|
3083
3686
|
/** Activate the invited user account (flips the account status flag). */
|
|
3084
3687
|
async activateUser(ctx) {
|
|
3085
3688
|
this.requireSubject(ctx);
|
|
3086
|
-
|
|
3689
|
+
if (ctx.accept) await this.currentInviteRow(ctx);
|
|
3690
|
+
const proved = ctx.email && ctx.admin?.inviteDelivery !== "return-link" && EMAIL_SHAPE.test(ctx.email) ? ctx.email : void 0;
|
|
3691
|
+
await this.users.activateAccount(ctx.subject, proved ? { verifiedEmail: proved } : {});
|
|
3087
3692
|
}
|
|
3088
3693
|
/**
|
|
3089
3694
|
* Emit the success-confirmation envelope. The downstream `finalize-auto-
|
|
@@ -3120,7 +3725,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3120
3725
|
if (ctx.postReset && err instanceof StepRetriableError) throw this.stampRecoveryExpiry(err);
|
|
3121
3726
|
throw err;
|
|
3122
3727
|
}
|
|
3123
|
-
if (input.newPassword !== input.confirmPassword) throw this.throwPublic(ctx, wf, { errors: { confirmPassword: "
|
|
3728
|
+
if (input.newPassword !== input.confirmPassword) throw this.throwPublic(ctx, wf, { errors: { confirmPassword: this.msg("PASSWORDS_DO_NOT_MATCH") } });
|
|
3729
|
+
if (ctx.accept) await this.assertInviteStillOpen(ctx);
|
|
3124
3730
|
try {
|
|
3125
3731
|
await this.users.setPassword(ctx.subject, input.newPassword);
|
|
3126
3732
|
} catch (err) {
|
|
@@ -3154,12 +3760,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3154
3760
|
finishWf({
|
|
3155
3761
|
message: {
|
|
3156
3762
|
level: "warn",
|
|
3157
|
-
text:
|
|
3763
|
+
text: this.msg("PASSWORD_CHANGE_TOO_RECENT")
|
|
3158
3764
|
},
|
|
3159
3765
|
next: {
|
|
3160
3766
|
trigger: "manual",
|
|
3161
3767
|
primary: {
|
|
3162
|
-
label: "
|
|
3768
|
+
label: this.msg("BACK"),
|
|
3163
3769
|
action: {
|
|
3164
3770
|
type: "redirect",
|
|
3165
3771
|
target: this.opts.loginUrl,
|
|
@@ -3183,7 +3789,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3183
3789
|
this.requireSubject(ctx);
|
|
3184
3790
|
const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.changePassword);
|
|
3185
3791
|
const input = wf.resolveInput();
|
|
3186
|
-
if (input.newPassword !== input.confirmPassword) throw this.throwPublic(ctx, wf, { errors: { confirmPassword: "
|
|
3792
|
+
if (input.newPassword !== input.confirmPassword) throw this.throwPublic(ctx, wf, { errors: { confirmPassword: this.msg("PASSWORDS_DO_NOT_MATCH") } });
|
|
3187
3793
|
try {
|
|
3188
3794
|
await this.users.changePassword(ctx.subject, input.currentPassword, input.newPassword, input.confirmPassword);
|
|
3189
3795
|
} catch (err) {
|
|
@@ -3210,7 +3816,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3210
3816
|
data: auth.buildLoginResponse(ctx.subject, issue),
|
|
3211
3817
|
message: {
|
|
3212
3818
|
level: "success",
|
|
3213
|
-
text:
|
|
3819
|
+
text: this.msg("PASSWORD_CHANGED")
|
|
3214
3820
|
}
|
|
3215
3821
|
};
|
|
3216
3822
|
useWfFinished().set({
|
|
@@ -3304,7 +3910,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3304
3910
|
},
|
|
3305
3911
|
message: {
|
|
3306
3912
|
level: "info",
|
|
3307
|
-
text:
|
|
3913
|
+
text: this.msg("ALL_MFA_METHODS_SET_UP")
|
|
3308
3914
|
}
|
|
3309
3915
|
};
|
|
3310
3916
|
else envelope = {
|
|
@@ -3315,7 +3921,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3315
3921
|
},
|
|
3316
3922
|
message: {
|
|
3317
3923
|
level: "info",
|
|
3318
|
-
text:
|
|
3924
|
+
text: this.msg("NO_MFA_CHANGES")
|
|
3319
3925
|
}
|
|
3320
3926
|
};
|
|
3321
3927
|
return envelope;
|
|
@@ -3405,7 +4011,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3405
4011
|
return;
|
|
3406
4012
|
}
|
|
3407
4013
|
const input = wf.resolveInput();
|
|
3408
|
-
if (!await this.users.verifyPassword(username, input.password)) throw this.throwPublic(ctx, wf, { errors: { password: "
|
|
4014
|
+
if (!await this.users.verifyPassword(username, input.password)) throw this.throwPublic(ctx, wf, { errors: { password: this.msg("INCORRECT_PASSWORD") } });
|
|
3409
4015
|
(ctx.otp ??= {}).verified = true;
|
|
3410
4016
|
}
|
|
3411
4017
|
/**
|
|
@@ -3450,12 +4056,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3450
4056
|
const action = sep >= 0 ? input.operation.slice(0, sep) : "";
|
|
3451
4057
|
const target = sep >= 0 ? input.operation.slice(sep + 1) : "";
|
|
3452
4058
|
if (action === "add") {
|
|
3453
|
-
if (!candidates.includes(target)) throw this.throwPublic(ctx, wf, { errors: { operation: "
|
|
4059
|
+
if (!candidates.includes(target)) throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("METHOD_UNAVAILABLE") } });
|
|
3454
4060
|
} else if (action === "replace" || action === "remove") {
|
|
3455
|
-
if (locked.has(target)) throw this.throwPublic(ctx, wf, { formMessage:
|
|
3456
|
-
if (!enrolled.some((e) => e.kind === target)) throw this.throwPublic(ctx, wf, { errors: { operation: "
|
|
3457
|
-
if (action === "remove" && addMfa.removeBlocked) throw this.throwPublic(ctx, wf, { formMessage:
|
|
3458
|
-
} else throw this.throwPublic(ctx, wf, { errors: { operation: "
|
|
4061
|
+
if (locked.has(target)) throw this.throwPublic(ctx, wf, { formMessage: this.msg("METHOD_NOT_CHANGEABLE") });
|
|
4062
|
+
if (!enrolled.some((e) => e.kind === target)) throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("UNKNOWN_METHOD") } });
|
|
4063
|
+
if (action === "remove" && addMfa.removeBlocked) throw this.throwPublic(ctx, wf, { formMessage: this.msg("KEEP_ONE_MFA_METHOD") });
|
|
4064
|
+
} else throw this.throwPublic(ctx, wf, { errors: { operation: this.msg("CHOOSE_OPTION") } });
|
|
3459
4065
|
addMfa.action = action;
|
|
3460
4066
|
addMfa.target = target;
|
|
3461
4067
|
const m = ctx.mfaEnroll ??= {};
|
|
@@ -3546,7 +4152,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3546
4152
|
if (action && this.resolvePincodeAltAction(ctx, action) === "resend") {
|
|
3547
4153
|
if (ctx.pincode?.resendAllowedAt && ctx.pincode.resendAllowedAt > Date.now()) {
|
|
3548
4154
|
const remainingSec = Math.ceil((ctx.pincode.resendAllowedAt - Date.now()) / 1e3);
|
|
3549
|
-
throw this.throwPublic(ctx, pincodeWf, { formMessage:
|
|
4155
|
+
throw this.throwPublic(ctx, pincodeWf, { formMessage: this.msg("RESEND_WAIT", { seconds: remainingSec }) });
|
|
3550
4156
|
}
|
|
3551
4157
|
const recipient = isEmail ? ctx.channel?.email : ctx.channel?.phone;
|
|
3552
4158
|
const code = this.mintPin(ctx, this.opts.mfa.pincodeLength, this.opts.mfa.pincodeTtlMs);
|
|
@@ -3713,13 +4319,16 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3713
4319
|
const input = wf.resolveInput();
|
|
3714
4320
|
const mfa = ctx.mfa ??= {};
|
|
3715
4321
|
const picked = (mfa.enrolledMethods ?? []).find((m) => m.methodName === input.methodName);
|
|
3716
|
-
if (!picked) throw this.throwPublic(ctx, wf, { errors: { methodName: "
|
|
4322
|
+
if (!picked) throw this.throwPublic(ctx, wf, { errors: { methodName: this.msg("UNKNOWN_MFA_METHOD") } });
|
|
3717
4323
|
if (picked.kind === "sms" || picked.kind === "email") {
|
|
3718
4324
|
const cooldownUntil = ctx.pincode?.channelCooldowns?.[picked.kind];
|
|
3719
4325
|
if (cooldownUntil && Date.now() < cooldownUntil) {
|
|
3720
4326
|
const waitSec = Math.ceil((cooldownUntil - Date.now()) / 1e3);
|
|
3721
4327
|
const channel = picked.kind === "sms" ? "SMS" : "email";
|
|
3722
|
-
throw this.throwPublic(ctx, wf, { formMessage:
|
|
4328
|
+
throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT_CHANNEL", {
|
|
4329
|
+
seconds: waitSec,
|
|
4330
|
+
channel
|
|
4331
|
+
}) });
|
|
3723
4332
|
}
|
|
3724
4333
|
}
|
|
3725
4334
|
mfa.method = picked.kind;
|
|
@@ -3790,7 +4399,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3790
4399
|
if (outcome === "resend") {
|
|
3791
4400
|
if (ctx.pincode?.resendAllowedAt && ctx.pincode.resendAllowedAt > Date.now()) {
|
|
3792
4401
|
const remainingSec = Math.ceil((ctx.pincode.resendAllowedAt - Date.now()) / 1e3);
|
|
3793
|
-
throw this.throwPublic(ctx, wf, { formMessage:
|
|
4402
|
+
throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT", { seconds: remainingSec }) });
|
|
3794
4403
|
}
|
|
3795
4404
|
delete ctx.pin;
|
|
3796
4405
|
delete ctx.pinExpire;
|
|
@@ -3850,12 +4459,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3850
4459
|
if (ctx.deviceTrust?.enabled && ctx.deviceTrust?.optIn) (ctx.trust ??= {}).rememberDevice = Boolean(input.rememberDevice);
|
|
3851
4460
|
} catch (err) {
|
|
3852
4461
|
if (err instanceof UserAuthError) {
|
|
3853
|
-
if (err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: "
|
|
3854
|
-
if (err.type === "INACTIVE") throw this.throwPublic(ctx, wf, { errors: { code: "
|
|
4462
|
+
if (err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: this.msg("ACCOUNT_LOCKED") });
|
|
4463
|
+
if (err.type === "INACTIVE") throw this.throwPublic(ctx, wf, { errors: { code: this.msg("INVALID_CODE") } });
|
|
3855
4464
|
if (err.type === "MFA_NOT_CONFIGURED") throw new HttpError$1(400, "No TOTP MFA configured");
|
|
3856
4465
|
if (err.type === "MFA_INVALID") {
|
|
3857
|
-
if (err.details?.lockEnds !== void 0) throw this.throwPublic(ctx, wf, { formMessage: "
|
|
3858
|
-
throw this.throwPublic(ctx, wf, { errors: { code: "
|
|
4466
|
+
if (err.details?.lockEnds !== void 0) throw this.throwPublic(ctx, wf, { formMessage: this.msg("ACCOUNT_LOCKED") });
|
|
4467
|
+
throw this.throwPublic(ctx, wf, { errors: { code: this.msg("INVALID_CODE") } });
|
|
3859
4468
|
}
|
|
3860
4469
|
if (err.type === "CAS_EXHAUSTED") throw new HttpError$1(409, err.message);
|
|
3861
4470
|
}
|
|
@@ -3899,7 +4508,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
3899
4508
|
return;
|
|
3900
4509
|
}
|
|
3901
4510
|
const picked = wf.resolveInput().method;
|
|
3902
|
-
if (!m.availableTransports.includes(picked)) throw this.throwPublic(ctx, wf, { errors: { method: "
|
|
4511
|
+
if (!m.availableTransports.includes(picked)) throw this.throwPublic(ctx, wf, { errors: { method: this.msg("UNKNOWN_METHOD") } });
|
|
3903
4512
|
m.method = picked;
|
|
3904
4513
|
}
|
|
3905
4514
|
return this.provisionTotpSecret(ctx);
|
|
@@ -4030,18 +4639,18 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4030
4639
|
const action = wf.resolveAction();
|
|
4031
4640
|
if (this.handleEnrollExit(ctx, action)) return void 0;
|
|
4032
4641
|
if (action === "resend") {
|
|
4033
|
-
if (m.method === "totp") throw this.throwPublic(ctx, wf, { formMessage: "
|
|
4642
|
+
if (m.method === "totp") throw this.throwPublic(ctx, wf, { formMessage: this.msg("TOTP_RESEND_NOT_APPLICABLE") });
|
|
4034
4643
|
const cooldown = ctx.pincode?.resendAllowedAt;
|
|
4035
4644
|
if (cooldown && Date.now() < cooldown) {
|
|
4036
4645
|
const waitSec = Math.ceil((cooldown - Date.now()) / 1e3);
|
|
4037
|
-
throw this.throwPublic(ctx, wf, { formMessage:
|
|
4646
|
+
throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT_ANOTHER", { seconds: waitSec }) });
|
|
4038
4647
|
}
|
|
4039
4648
|
await this.mintAndSendEnrollPincode(ctx, m.address);
|
|
4040
4649
|
return;
|
|
4041
4650
|
}
|
|
4042
4651
|
const input = wf.resolveInput();
|
|
4043
4652
|
if (m.method === "totp") {
|
|
4044
|
-
if (verifyTotpCode(m.secret, input.code) === null) throw this.throwPublic(ctx, wf, { errors: { code: "
|
|
4653
|
+
if (verifyTotpCode(m.secret, input.code) === null) throw this.throwPublic(ctx, wf, { errors: { code: this.msg("INVALID_CODE") } });
|
|
4045
4654
|
} else {
|
|
4046
4655
|
const pinErr = this.verifyPin(ctx, input.code);
|
|
4047
4656
|
if (pinErr) throw this.throwPublic(ctx, wf, { errors: pinErr });
|
|
@@ -4059,6 +4668,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4059
4668
|
*/
|
|
4060
4669
|
async confirmEnrolledFactor(ctx) {
|
|
4061
4670
|
this.requireSubject(ctx);
|
|
4671
|
+
if (ctx.accept) await this.assertInviteStillOpen(ctx);
|
|
4062
4672
|
const username = ctx.subject;
|
|
4063
4673
|
const m = ctx.mfaEnroll ??= {};
|
|
4064
4674
|
const methodName = m.method;
|
|
@@ -4235,7 +4845,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4235
4845
|
const cfg = ctx.sessionPolicy?.concurrencyLimit;
|
|
4236
4846
|
if (!cfg) return void 0;
|
|
4237
4847
|
const wf = this.useAtscriptWfPublic(ctx, this.opts.forms.concurrencyLimit);
|
|
4238
|
-
if (cfg.onLimit === "reject") throw this.throwPublic(ctx, wf, { formMessage: "
|
|
4848
|
+
if (cfg.onLimit === "reject") throw this.throwPublic(ctx, wf, { formMessage: this.msg("SESSION_LIMIT_REACHED") });
|
|
4239
4849
|
wf.resolveInput();
|
|
4240
4850
|
if (ctx.subject) await this.logoutOtherSessions(ctx.subject);
|
|
4241
4851
|
}
|
|
@@ -4254,6 +4864,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4254
4864
|
const group = ctx.consents ?? {};
|
|
4255
4865
|
const pending = group.pending ?? [];
|
|
4256
4866
|
if (pending.length === 0) return void 0;
|
|
4867
|
+
if (ctx.accept) await this.assertInviteStillOpen(ctx);
|
|
4257
4868
|
const accepted = new Set(group.accepted ?? []);
|
|
4258
4869
|
const at = group.decidedAt ?? Date.now();
|
|
4259
4870
|
const events = pending.map((p) => {
|
|
@@ -4469,7 +5080,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4469
5080
|
if (!authz || !req) {
|
|
4470
5081
|
finishWf({ message: {
|
|
4471
5082
|
level: "error",
|
|
4472
|
-
text:
|
|
5083
|
+
text: this.msg("AUTHZ_EXPIRED")
|
|
4473
5084
|
} });
|
|
4474
5085
|
return;
|
|
4475
5086
|
}
|
|
@@ -4477,7 +5088,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4477
5088
|
await pending.delete(authz.handle);
|
|
4478
5089
|
finishWf({ message: {
|
|
4479
5090
|
level: "error",
|
|
4480
|
-
text:
|
|
5091
|
+
text: this.msg("AUTHZ_BROWSER_MISMATCH")
|
|
4481
5092
|
} });
|
|
4482
5093
|
return;
|
|
4483
5094
|
}
|
|
@@ -4533,7 +5144,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4533
5144
|
if (!handle || !req) {
|
|
4534
5145
|
finishWf({ message: {
|
|
4535
5146
|
level: "error",
|
|
4536
|
-
text:
|
|
5147
|
+
text: this.msg("AUTHZ_EXPIRED")
|
|
4537
5148
|
} });
|
|
4538
5149
|
return;
|
|
4539
5150
|
}
|
|
@@ -4541,7 +5152,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4541
5152
|
await pending.delete(handle);
|
|
4542
5153
|
finishWf({ message: {
|
|
4543
5154
|
level: "error",
|
|
4544
|
-
text:
|
|
5155
|
+
text: this.msg("AUTHZ_FAILED")
|
|
4545
5156
|
} });
|
|
4546
5157
|
return;
|
|
4547
5158
|
}
|
|
@@ -4620,12 +5231,12 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4620
5231
|
if (stillLocked) finishWf({
|
|
4621
5232
|
message: {
|
|
4622
5233
|
level: "warn",
|
|
4623
|
-
text:
|
|
5234
|
+
text: this.msg("PASSWORD_UPDATED_STILL_LOCKED")
|
|
4624
5235
|
},
|
|
4625
5236
|
next: {
|
|
4626
5237
|
trigger: "manual",
|
|
4627
5238
|
primary: {
|
|
4628
|
-
label: "
|
|
5239
|
+
label: this.msg("BACK_TO_SIGN_IN"),
|
|
4629
5240
|
action: {
|
|
4630
5241
|
type: "redirect",
|
|
4631
5242
|
target,
|
|
@@ -4637,7 +5248,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4637
5248
|
else finishWf({
|
|
4638
5249
|
message: {
|
|
4639
5250
|
level: "success",
|
|
4640
|
-
text:
|
|
5251
|
+
text: this.msg("PASSWORD_UPDATED_REDIRECTING")
|
|
4641
5252
|
},
|
|
4642
5253
|
next: {
|
|
4643
5254
|
trigger: "auto",
|
|
@@ -4647,7 +5258,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4647
5258
|
target,
|
|
4648
5259
|
reason: "reset-success"
|
|
4649
5260
|
},
|
|
4650
|
-
skipButton: { label: "
|
|
5261
|
+
skipButton: { label: this.msg("GO_NOW") }
|
|
4651
5262
|
}
|
|
4652
5263
|
});
|
|
4653
5264
|
(ctx.completion ??= {}).redirectUrl = target;
|
|
@@ -4698,7 +5309,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4698
5309
|
ctx.autoLogin = true;
|
|
4699
5310
|
if (!policy.allowSignup) finishWf({ message: {
|
|
4700
5311
|
level: "info",
|
|
4701
|
-
text:
|
|
5312
|
+
text: this.msg("SIGNUP_DISABLED")
|
|
4702
5313
|
} });
|
|
4703
5314
|
};
|
|
4704
5315
|
const result = this.resolveSignupPolicy(ctx);
|
|
@@ -4769,7 +5380,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4769
5380
|
finishWf({
|
|
4770
5381
|
message: {
|
|
4771
5382
|
level: "info",
|
|
4772
|
-
text:
|
|
5383
|
+
text: this.msg("ALREADY_HAVE_ACCOUNT")
|
|
4773
5384
|
},
|
|
4774
5385
|
next: {
|
|
4775
5386
|
trigger: "immediate",
|
|
@@ -4851,7 +5462,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
4851
5462
|
finishWf({
|
|
4852
5463
|
message: {
|
|
4853
5464
|
level: "success",
|
|
4854
|
-
text:
|
|
5465
|
+
text: this.msg("ACCOUNT_LINKED")
|
|
4855
5466
|
},
|
|
4856
5467
|
next: {
|
|
4857
5468
|
trigger: "immediate",
|
|
@@ -5066,7 +5677,7 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
5066
5677
|
const cooldown = pending.resendAllowedAt;
|
|
5067
5678
|
if (cooldown && Date.now() < cooldown) {
|
|
5068
5679
|
const waitSec = Math.ceil((cooldown - Date.now()) / 1e3);
|
|
5069
|
-
throw this.throwPublic(ctx, wf, { formMessage:
|
|
5680
|
+
throw this.throwPublic(ctx, wf, { formMessage: this.msg("RESEND_WAIT_ANOTHER", { seconds: waitSec }) });
|
|
5070
5681
|
}
|
|
5071
5682
|
const sentTo = await this.deliverPendingLinkPin(candidate, pending);
|
|
5072
5683
|
if (sentTo === null) {
|
|
@@ -5083,8 +5694,8 @@ let AuthWorkflow = _AuthWorkflow = class AuthWorkflow {
|
|
|
5083
5694
|
} else try {
|
|
5084
5695
|
await this.users.login(candidate.username, input.password ?? "", this.lockoutOverride(ctx));
|
|
5085
5696
|
} catch (err) {
|
|
5086
|
-
if (err instanceof UserAuthError && err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: "
|
|
5087
|
-
throw this.throwPublic(ctx, wf, { errors: { password: "
|
|
5697
|
+
if (err instanceof UserAuthError && err.type === "LOCKED") throw this.throwPublic(ctx, wf, { formMessage: this.msg("ACCOUNT_LOCKED") });
|
|
5698
|
+
throw this.throwPublic(ctx, wf, { errors: { password: this.msg("INVALID_PASSWORD") } });
|
|
5088
5699
|
}
|
|
5089
5700
|
if (this.isAccountBlocked(candidate)) {
|
|
5090
5701
|
delete ctx.pendingLink;
|
|
@@ -5219,7 +5830,7 @@ __decorate([
|
|
|
5219
5830
|
__decorateParam(0, WorkflowParam("context")),
|
|
5220
5831
|
__decorateMetadata("design:type", Function),
|
|
5221
5832
|
__decorateMetadata("design:paramtypes", [Object]),
|
|
5222
|
-
__decorateMetadata("design:returntype",
|
|
5833
|
+
__decorateMetadata("design:returntype", Promise)
|
|
5223
5834
|
], AuthWorkflow.prototype, "initInviteAdmin", null);
|
|
5224
5835
|
__decorate([
|
|
5225
5836
|
Step("init-invite-accept"),
|
|
@@ -5437,6 +6048,15 @@ __decorate([
|
|
|
5437
6048
|
__decorateMetadata("design:paramtypes", [Object]),
|
|
5438
6049
|
__decorateMetadata("design:returntype", Promise)
|
|
5439
6050
|
], AuthWorkflow.prototype, "buildUserExtras", null);
|
|
6051
|
+
__decorate([
|
|
6052
|
+
Step("assert-invite-created"),
|
|
6053
|
+
ArbacResource("auth.invite"),
|
|
6054
|
+
ArbacAction("start"),
|
|
6055
|
+
__decorateParam(0, WorkflowParam("context")),
|
|
6056
|
+
__decorateMetadata("design:type", Function),
|
|
6057
|
+
__decorateMetadata("design:paramtypes", [Object]),
|
|
6058
|
+
__decorateMetadata("design:returntype", void 0)
|
|
6059
|
+
], AuthWorkflow.prototype, "assertInviteCreated", null);
|
|
5440
6060
|
__decorate([
|
|
5441
6061
|
Step("create-user"),
|
|
5442
6062
|
ArbacResource("auth.invite"),
|
|
@@ -5463,6 +6083,14 @@ __decorate([
|
|
|
5463
6083
|
__decorateMetadata("design:paramtypes", [Object]),
|
|
5464
6084
|
__decorateMetadata("design:returntype", Promise)
|
|
5465
6085
|
], AuthWorkflow.prototype, "checkPendingInvitation", null);
|
|
6086
|
+
__decorate([
|
|
6087
|
+
Step("choose-username"),
|
|
6088
|
+
Public(),
|
|
6089
|
+
__decorateParam(0, WorkflowParam("context")),
|
|
6090
|
+
__decorateMetadata("design:type", Function),
|
|
6091
|
+
__decorateMetadata("design:paramtypes", [Object]),
|
|
6092
|
+
__decorateMetadata("design:returntype", Promise)
|
|
6093
|
+
], AuthWorkflow.prototype, "chooseUsername", null);
|
|
5466
6094
|
__decorate([
|
|
5467
6095
|
Step("idempotent-redirect"),
|
|
5468
6096
|
Public(),
|
|
@@ -6102,6 +6730,10 @@ __decorate([
|
|
|
6102
6730
|
id: "create-user",
|
|
6103
6731
|
condition: (ctx) => !!(ctx.email && !ctx.subject && !!ctx.admin?.userExtras)
|
|
6104
6732
|
},
|
|
6733
|
+
{
|
|
6734
|
+
id: "assert-invite-created",
|
|
6735
|
+
condition: (ctx) => !!ctx.email && !ctx.subject
|
|
6736
|
+
},
|
|
6105
6737
|
{
|
|
6106
6738
|
id: "send-email",
|
|
6107
6739
|
condition: (ctx) => !!ctx.subject
|
|
@@ -6116,6 +6748,11 @@ __decorate([
|
|
|
6116
6748
|
id: "idempotent-redirect",
|
|
6117
6749
|
condition: (ctx) => !!ctx.accept?.alreadyAccepted
|
|
6118
6750
|
},
|
|
6751
|
+
{ break: (ctx) => !!ctx.accept?.alreadyAccepted },
|
|
6752
|
+
{
|
|
6753
|
+
id: "choose-username",
|
|
6754
|
+
condition: (ctx) => !!ctx.accept?.chooseUsername && !ctx.accept?.usernameChosen
|
|
6755
|
+
},
|
|
6119
6756
|
{ id: "prepare-consents" },
|
|
6120
6757
|
{ id: "prepare-semantic-flags" },
|
|
6121
6758
|
...passwordPhaseSchema,
|
|
@@ -6329,6 +6966,10 @@ const CHANGE_PASSWORD_WORKFLOW = "auth/change-password/flow";
|
|
|
6329
6966
|
* `/auth/trigger`.
|
|
6330
6967
|
*/
|
|
6331
6968
|
const ADD_MFA_WORKFLOW = "auth/add-mfa/flow";
|
|
6969
|
+
/** The post-redemption route's single "not found" answer. */
|
|
6970
|
+
function inviteNotFound() {
|
|
6971
|
+
return new HttpError$1(404, "Invite not found");
|
|
6972
|
+
}
|
|
6332
6973
|
/** Prefer an explicit body field, fall back to the refresh cookie when enabled. */
|
|
6333
6974
|
function resolveRefreshToken(auth, body) {
|
|
6334
6975
|
if (typeof body?.refreshToken === "string") return body.refreshToken;
|
|
@@ -6389,7 +7030,8 @@ let AuthController = class AuthController {
|
|
|
6389
7030
|
}
|
|
6390
7031
|
auth.writeCookies(issue);
|
|
6391
7032
|
const validated = await this.auth.validate(issue.accessToken);
|
|
6392
|
-
|
|
7033
|
+
const fromBody = typeof body?.refreshToken === "string";
|
|
7034
|
+
return auth.buildLoginResponse(validated?.userId ?? "", issue, fromBody ? { exposeTokens: true } : void 0);
|
|
6393
7035
|
}
|
|
6394
7036
|
status() {
|
|
6395
7037
|
const auth = useAuth().getAuthContext();
|
|
@@ -6432,29 +7074,41 @@ let AuthController = class AuthController {
|
|
|
6432
7074
|
* but the user-id baked into the magic-link URL by `buildMagicLinkUrl(…, {
|
|
6433
7075
|
* userId })` lets the SPA resolve the "already accepted" condition itself.
|
|
6434
7076
|
*
|
|
6435
|
-
* `@Public()` — invitees aren't signed in at this point.
|
|
7077
|
+
* `@Public()` — invitees aren't signed in at this point. Rate limited
|
|
7078
|
+
* (`30/5m` per IP, enforced when `rateLimitInterceptors` are installed); an
|
|
7079
|
+
* unknown id and a still-pending invite get the same 404.
|
|
6436
7080
|
*
|
|
6437
7081
|
* Defaults for `loginUrl` / `alreadyAcceptedRedirectUrl` mirror the unified
|
|
6438
7082
|
* `AuthWorkflow` defaults (`/login` / `/login`). Subclasses override
|
|
6439
7083
|
* `resolveInvitePostRedemption()` to read live workflow opts.
|
|
6440
7084
|
*/
|
|
6441
7085
|
async invitePostRedemption(uid) {
|
|
7086
|
+
if (!this.invitePostRedemptionEnabled()) throw inviteNotFound();
|
|
6442
7087
|
if (!uid) throw new HttpError$1(400, "Missing uid query parameter");
|
|
6443
7088
|
if (!this.users) throw new HttpError$1(500, "UserService not wired — cannot resolve post-redemption state");
|
|
6444
7089
|
let user;
|
|
6445
7090
|
try {
|
|
6446
7091
|
user = await this.users.getUser(uid);
|
|
6447
7092
|
} catch (err) {
|
|
6448
|
-
if (err instanceof UserAuthError && err.type === "NOT_FOUND") throw
|
|
7093
|
+
if (err instanceof UserAuthError && err.type === "NOT_FOUND") throw inviteNotFound();
|
|
6449
7094
|
throw err;
|
|
6450
7095
|
}
|
|
6451
|
-
if (user.account?.pendingInvitation) throw
|
|
7096
|
+
if (user.account?.pendingInvitation) throw inviteNotFound();
|
|
6452
7097
|
return {
|
|
6453
7098
|
finished: true,
|
|
6454
7099
|
...buildInviteAlreadyAcceptedEnvelope(this.resolveInvitePostRedemption())
|
|
6455
7100
|
};
|
|
6456
7101
|
}
|
|
6457
7102
|
/**
|
|
7103
|
+
* Whether `GET auth/invite/post-redemption` is served. Default `true`.
|
|
7104
|
+
* Override to return `false` when the app does not use magic-link invites —
|
|
7105
|
+
* the route then answers 404 for every id (a subclass cannot unregister an
|
|
7106
|
+
* inherited route).
|
|
7107
|
+
*/
|
|
7108
|
+
invitePostRedemptionEnabled() {
|
|
7109
|
+
return true;
|
|
7110
|
+
}
|
|
7111
|
+
/**
|
|
6458
7112
|
* URLs used by `invitePostRedemption`. Defaults mirror the unified
|
|
6459
7113
|
* `AuthWorkflow` resolved opts so subclasses that customize either of
|
|
6460
7114
|
* those options can override here to keep the side route in sync.
|
|
@@ -6526,6 +7180,7 @@ __decorate([
|
|
|
6526
7180
|
__decorate([
|
|
6527
7181
|
Get("invite/post-redemption"),
|
|
6528
7182
|
Public(),
|
|
7183
|
+
RateLimit("30/5m"),
|
|
6529
7184
|
__decorateParam(0, Query("uid")),
|
|
6530
7185
|
__decorateMetadata("design:type", Function),
|
|
6531
7186
|
__decorateMetadata("design:paramtypes", [Object]),
|
|
@@ -6630,190 +7285,6 @@ SessionsController = __decorate([
|
|
|
6630
7285
|
__decorateMetadata("design:paramtypes", [typeof AuthCredential === "undefined" ? Object : AuthCredential, typeof SessionEnricherProvider === "undefined" ? Object : SessionEnricherProvider])
|
|
6631
7286
|
], SessionsController);
|
|
6632
7287
|
//#endregion
|
|
6633
|
-
//#region src/rate-limit/composables.ts
|
|
6634
|
-
/**
|
|
6635
|
-
* Internal: the decision for this event, written by `rateLimitInterceptors`.
|
|
6636
|
-
* Its presence also serves as the "already evaluated" marker that prevents
|
|
6637
|
-
* double counting when the interceptor pair is registered more than once
|
|
6638
|
-
* (global + `@Intercept`) — moost runs `before` hooks sequentially, so a
|
|
6639
|
-
* duplicate instance always observes the first one's write.
|
|
6640
|
-
*/
|
|
6641
|
-
const rateLimitDecisionKey = key("aooth.rateLimit.decision");
|
|
6642
|
-
/**
|
|
6643
|
-
* Internal: named rate-limit subjects for this event — subject kind
|
|
6644
|
-
* (`'user'`, `'tenant'`, …) → resolved caller identity, written via
|
|
6645
|
-
* {@link setRateLimitSubject} and read by the post-guard rate-limit phase.
|
|
6646
|
-
*/
|
|
6647
|
-
const rateLimitSubjectsKey = key("aooth.rateLimit.subjects");
|
|
6648
|
-
/**
|
|
6649
|
-
* Supply the rate-limit subject for a named key strategy — the seam for
|
|
6650
|
-
* custom IAMs / tenant resolvers. Call from GUARD-priority (or earlier)
|
|
6651
|
-
* code; the value is used VERBATIM as the counter subject (include your own
|
|
6652
|
-
* prefix, e.g. `iam:<sub>`) and always wins over the built-in `user` /
|
|
6653
|
-
* `session` derivations. Full contract: docs `/moost/rate-limit`.
|
|
6654
|
-
*/
|
|
6655
|
-
function setRateLimitSubject(kind, subject, ctx = current()) {
|
|
6656
|
-
const subjects = ctx.has(rateLimitSubjectsKey) ? ctx.get(rateLimitSubjectsKey) : {};
|
|
6657
|
-
subjects[kind] = subject;
|
|
6658
|
-
ctx.set(rateLimitSubjectsKey, subjects);
|
|
6659
|
-
}
|
|
6660
|
-
/** Read a named rate-limit subject set for this event (or `undefined`). */
|
|
6661
|
-
function getRateLimitSubject(kind, ctx = current()) {
|
|
6662
|
-
return ctx.has(rateLimitSubjectsKey) ? ctx.get(rateLimitSubjectsKey)[kind] : void 0;
|
|
6663
|
-
}
|
|
6664
|
-
/**
|
|
6665
|
-
* Read the current event's rate-limit state. A plain function (not a cached
|
|
6666
|
-
* wook) — it's a single slot read, and workflow child events inherit the
|
|
6667
|
-
* HTTP parent's slot transparently.
|
|
6668
|
-
*/
|
|
6669
|
-
function useRateLimit(ctx = current()) {
|
|
6670
|
-
return { decision: ctx.has(rateLimitDecisionKey) ? ctx.get(rateLimitDecisionKey) : null };
|
|
6671
|
-
}
|
|
6672
|
-
//#endregion
|
|
6673
|
-
//#region src/rate-limit/interceptor.ts
|
|
6674
|
-
/**
|
|
6675
|
-
* Global interceptor PAIR enforcing `@RateLimit` metadata (RL.spec.md §5.2)
|
|
6676
|
-
* — register with spread:
|
|
6677
|
-
*
|
|
6678
|
-
* ```ts
|
|
6679
|
-
* app.applyGlobalInterceptors(
|
|
6680
|
-
* authGuardInterceptor({ ... }),
|
|
6681
|
-
* ...rateLimitInterceptors({ limiter, trustProxy: true }),
|
|
6682
|
-
* )
|
|
6683
|
-
* ```
|
|
6684
|
-
*
|
|
6685
|
-
* Two phases, because the primary target is public endpoints and
|
|
6686
|
-
* `authGuardInterceptor` is NOT free there — with any `Authorization`
|
|
6687
|
-
* header present it runs full credential validation before tolerating the
|
|
6688
|
-
* failure on `@Public()` routes:
|
|
6689
|
-
*
|
|
6690
|
-
* - `BEFORE_GUARD` phase owns routes whose effective key strategy is
|
|
6691
|
-
* `'ip'` or a custom resolver — floods are rejected before any
|
|
6692
|
-
* token/credential work.
|
|
6693
|
-
* - `AFTER_GUARD` phase owns `'user'` / `'auto'` keyed routes — those need
|
|
6694
|
-
* the auth context `useAuth()` reads, and by definition target
|
|
6695
|
-
* authenticated traffic where the guard must run anyway.
|
|
6696
|
-
*
|
|
6697
|
-
* Ownership is static per route (from metadata/options), so exactly one
|
|
6698
|
-
* phase evaluates each event; the decision event-slot additionally guards
|
|
6699
|
-
* against double counting when the pair is also attached per-controller
|
|
6700
|
-
* (see {@link RateLimited}).
|
|
6701
|
-
*
|
|
6702
|
-
* On rejection: draft `RateLimit-*` headers + `Retry-After` are written to
|
|
6703
|
-
* the accumulated response (they survive the throw — wooks renders the error
|
|
6704
|
-
* onto the same `HttpResponse`), then `HttpError(429, message)` is thrown.
|
|
6705
|
-
*/
|
|
6706
|
-
function rateLimitInterceptors(opts) {
|
|
6707
|
-
const defaultRules = opts?.rules?.map((r) => parseRateLimitRule(r));
|
|
6708
|
-
const limiter = opts?.limiter ?? new RateLimiter$1();
|
|
6709
|
-
const emitHeaders = opts?.headers ?? true;
|
|
6710
|
-
const ipOpts = { trustProxy: opts?.trustProxy ?? false };
|
|
6711
|
-
const routeConfigs = /* @__PURE__ */ new WeakMap();
|
|
6712
|
-
const resolveRouteConfig = (cc) => {
|
|
6713
|
-
const ctor = cc.getController().constructor;
|
|
6714
|
-
const method = String(cc.getMethod());
|
|
6715
|
-
let byMethod = routeConfigs.get(ctor);
|
|
6716
|
-
if (!byMethod) {
|
|
6717
|
-
byMethod = /* @__PURE__ */ new Map();
|
|
6718
|
-
routeConfigs.set(ctor, byMethod);
|
|
6719
|
-
}
|
|
6720
|
-
const cached = byMethod.get(method);
|
|
6721
|
-
if (cached !== void 0) return cached;
|
|
6722
|
-
const cMeta = cc.getControllerMeta();
|
|
6723
|
-
const mMeta = cc.getMethodMeta();
|
|
6724
|
-
let config = null;
|
|
6725
|
-
const disabled = mMeta?.rateLimitDisabled ?? cMeta?.rateLimitDisabled ?? false;
|
|
6726
|
-
const rules = mMeta?.rateLimitRules ?? cMeta?.rateLimitRules ?? defaultRules;
|
|
6727
|
-
if (!disabled && rules && rules.length > 0) {
|
|
6728
|
-
const metaOpts = mMeta?.rateLimitOptions ?? cMeta?.rateLimitOptions;
|
|
6729
|
-
const rawKey = metaOpts?.key ?? opts?.key ?? "ip";
|
|
6730
|
-
const keyStrategy = rawKey === "auto" ? "user" : rawKey;
|
|
6731
|
-
config = {
|
|
6732
|
-
rules,
|
|
6733
|
-
keyStrategy,
|
|
6734
|
-
postGuardKeyed: typeof keyStrategy === "string" && keyStrategy !== "ip",
|
|
6735
|
-
scope: metaOpts?.id ?? `${ctor.name}.${method}`,
|
|
6736
|
-
...(metaOpts?.message ?? opts?.message) !== void 0 && { defaultMessage: metaOpts?.message ?? opts?.message },
|
|
6737
|
-
policyHeader: rules.map((p) => `${p.limit};w=${Math.max(1, Math.round(p.window / 1e3))}`).join(", ")
|
|
6738
|
-
};
|
|
6739
|
-
}
|
|
6740
|
-
byMethod.set(method, config);
|
|
6741
|
-
return config;
|
|
6742
|
-
};
|
|
6743
|
-
const evaluate = async (phase) => {
|
|
6744
|
-
const ctx = current();
|
|
6745
|
-
if (ctx.get(eventTypeKey) !== "http") return;
|
|
6746
|
-
if (ctx.has(rateLimitDecisionKey)) return;
|
|
6747
|
-
const config = resolveRouteConfig(useControllerContext(ctx));
|
|
6748
|
-
if (!config) return;
|
|
6749
|
-
if (config.postGuardKeyed !== (phase === "post")) return;
|
|
6750
|
-
const subject = await resolveSubject(config.keyStrategy, ipOpts, ctx);
|
|
6751
|
-
const decision = await limiter.check(config.scope, subject, config.rules, { ...config.defaultMessage !== void 0 && { defaultMessage: config.defaultMessage } });
|
|
6752
|
-
ctx.set(rateLimitDecisionKey, decision);
|
|
6753
|
-
const response = useResponse(ctx);
|
|
6754
|
-
if (emitHeaders) {
|
|
6755
|
-
response.setHeader("ratelimit-limit", String(decision.limit));
|
|
6756
|
-
response.setHeader("ratelimit-remaining", String(decision.remaining));
|
|
6757
|
-
response.setHeader("ratelimit-reset", String(Math.ceil(decision.resetAfterMs / 1e3)));
|
|
6758
|
-
response.setHeader("ratelimit-policy", config.policyHeader);
|
|
6759
|
-
}
|
|
6760
|
-
if (!decision.allowed) {
|
|
6761
|
-
response.setHeader("retry-after", String(Math.ceil(decision.resetAfterMs / 1e3)));
|
|
6762
|
-
throw new HttpError(429, decision.message ?? "Too many requests");
|
|
6763
|
-
}
|
|
6764
|
-
};
|
|
6765
|
-
return [defineBeforeInterceptor(() => evaluate("pre"), TInterceptorPriority.BEFORE_GUARD), defineBeforeInterceptor(() => evaluate("post"), TInterceptorPriority.AFTER_GUARD)];
|
|
6766
|
-
}
|
|
6767
|
-
async function resolveSubject(strategy, ipOpts, ctx) {
|
|
6768
|
-
if (typeof strategy === "function") return await strategy();
|
|
6769
|
-
if (strategy !== "ip") {
|
|
6770
|
-
const subject = getRateLimitSubject(strategy, ctx);
|
|
6771
|
-
if (subject !== void 0) return subject;
|
|
6772
|
-
const auth = strategy === "user" || strategy === "session" ? useAuth(ctx).getAuthContext() : null;
|
|
6773
|
-
if (strategy === "user" && auth?.userId !== void 0) return `u:${auth.userId}`;
|
|
6774
|
-
if (strategy === "session" && auth?.sessionId !== void 0) return `s:${auth.sessionId}`;
|
|
6775
|
-
}
|
|
6776
|
-
return `ip:${useRequest(ctx).getIp(ipOpts)}`;
|
|
6777
|
-
}
|
|
6778
|
-
//#endregion
|
|
6779
|
-
//#region src/rate-limit/mate.ts
|
|
6780
|
-
function getRateLimitMate() {
|
|
6781
|
-
return getMoostMate();
|
|
6782
|
-
}
|
|
6783
|
-
//#endregion
|
|
6784
|
-
//#region src/rate-limit/decorator.ts
|
|
6785
|
-
function RateLimit(...args) {
|
|
6786
|
-
const mate = getRateLimitMate();
|
|
6787
|
-
if (args.length === 1 && args[0] === false) return mate.decorate("rateLimitDisabled", true);
|
|
6788
|
-
const inputs = [...args];
|
|
6789
|
-
let options;
|
|
6790
|
-
const last = inputs[inputs.length - 1];
|
|
6791
|
-
if (typeof last === "object" && last !== null && !("limit" in last)) options = inputs.pop();
|
|
6792
|
-
if (inputs.length === 0) throw new Error("@RateLimit requires at least one rule (or the literal `false` to opt out)");
|
|
6793
|
-
const rules = inputs.map((r) => parseRateLimitRule(r));
|
|
6794
|
-
return mate.decorate((meta) => {
|
|
6795
|
-
meta.rateLimitRules = rules;
|
|
6796
|
-
if (options) meta.rateLimitOptions = options;
|
|
6797
|
-
return meta;
|
|
6798
|
-
});
|
|
6799
|
-
}
|
|
6800
|
-
/**
|
|
6801
|
-
* Decorator-factory sugar for attaching the `rateLimitInterceptors(opts)`
|
|
6802
|
-
* PAIR to a specific controller or method instead of globally — the
|
|
6803
|
-
* `AuthGuarded` counterpart. Attaching the pair (not one phase) matters:
|
|
6804
|
-
* dropping the pre-guard def loses flood protection for ip-keyed routes,
|
|
6805
|
-
* dropping the post-guard def silently disables `key: 'user'` routes.
|
|
6806
|
-
*/
|
|
6807
|
-
function RateLimited(opts) {
|
|
6808
|
-
const [pre, post] = rateLimitInterceptors(opts);
|
|
6809
|
-
const interceptPre = Intercept(pre);
|
|
6810
|
-
const interceptPost = Intercept(post);
|
|
6811
|
-
return ((target, key, descriptor) => {
|
|
6812
|
-
interceptPre(target, key, descriptor);
|
|
6813
|
-
interceptPost(target, key, descriptor);
|
|
6814
|
-
});
|
|
6815
|
-
}
|
|
6816
|
-
//#endregion
|
|
6817
7288
|
//#region src/oauth/oauth-tokens.ts
|
|
6818
7289
|
/**
|
|
6819
7290
|
* Explicit string DI token for the ABSTRACT `FederatedIdentityStore`.
|
|
@@ -7536,4 +8007,4 @@ function createAuthEmailOutlet(deps) {
|
|
|
7536
8007
|
});
|
|
7537
8008
|
}
|
|
7538
8009
|
//#endregion
|
|
7539
|
-
export { ADD_MFA_WORKFLOW, AUTHZ_BINDING_COOKIE, AUTH_CODE_STORE_TOKEN, AuthController, AuthGuarded, AuthWorkflow, AuthorizeController, AuthorizeRuntime, CHANGE_PASSWORD_WORKFLOW, CLIENT_REDIRECT_POLICY_TOKEN, ConsentStore, DEFAULT_AUTH_WORKFLOWS, DYNAMIC_CLIENT_STORE_TOKEN, DynamicClientRegistration, FEDERATED_IDENTITY_STORE_TOKEN, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, Public, RESERVED_USER_KEYS, RateLimit, RateLimitStoreMemory, RateLimited, RateLimiter, SessionEnricherProvider, SessionsController, UserId, WfTrigger, WfTriggerProvider, authGuardInterceptor, authzBindingCookieAttrs, buildAuthorizationServerMetadata, buildInviteAlreadyAcceptedEnvelope, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, createAuthEmailOutlet, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, getRateLimitMate, getRateLimitSubject, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, resolveOAuthRedirect, setRateLimitSubject, stripReservedUserKeys, useAuth, useRateLimit };
|
|
8010
|
+
export { ADD_MFA_WORKFLOW, AOOTH_MESSAGES, AUTHZ_BINDING_COOKIE, AUTH_CODE_STORE_TOKEN, AuthController, AuthGuarded, AuthWorkflow, AuthorizeController, AuthorizeRuntime, CHANGE_PASSWORD_WORKFLOW, CLIENT_REDIRECT_POLICY_TOKEN, ConsentStore, DEFAULT_AUTH_WORKFLOWS, DYNAMIC_CLIENT_STORE_TOKEN, DynamicClientRegistration, FEDERATED_IDENTITY_STORE_TOKEN, INVITE_OUTLET, OAUTH_CSRF_COOKIE, OAuthController, OAuthRuntime, PENDING_AUTHORIZATION_STORE_TOKEN, Public, RESERVED_USER_KEYS, RateLimit, RateLimitStoreMemory, RateLimited, RateLimiter, SessionEnricherProvider, SessionsController, UserId, WfTrigger, WfTriggerProvider, authGuardInterceptor, authzBindingCookieAttrs, buildAuthorizationServerMetadata, buildInviteAlreadyAcceptedEnvelope, buildProtectedResourceMetadata, buildWwwAuthenticateBearerChallenge, canonicalizeIssuer, createAuthEmailOutlet, createInviteOutlet, deriveWfStateSecret, generateMagicLinkToken, getAuthMate, getRateLimitMate, getRateLimitSubject, haversineKm, humanizeUserAgent, isSafeRelativeRedirect, oauthCsrfCookieAttrs, parseInviteRoles, rateLimitInterceptors, renderAoothMessage, resolveAoothMessage, resolveOAuthRedirect, setRateLimitSubject, stripReservedUserKeys, useAuth, useRateLimit };
|