@payez/next-mvp 4.7.9 → 4.8.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.
@@ -57,9 +57,14 @@ export interface SessionPointer {
57
57
  clientId: string;
58
58
  }
59
59
 
60
+ /** PAY-2339: which check could not answer. A fixed, machine-readable value: consumers never parse message text. */
61
+ export type UnavailableCheck = 'revocation' | 'viability';
62
+
60
63
  export interface SessionStatus {
61
64
  exists: boolean | null; // null = check failed/timeout
62
65
  forceInvalid: boolean | null; // null = check failed/timeout
66
+ /** PAY-2339: the revocation backend could not answer and this app HOLDS (revocationFailMode 'hold'): no sign-out. */
67
+ unavailable?: boolean;
63
68
  requires2FA: boolean;
64
69
  twoFactorComplete: boolean;
65
70
  }
@@ -67,7 +72,7 @@ export interface SessionStatus {
67
72
  export type AuthAction =
68
73
  | { type: 'allow' }
69
74
  | { type: 'redirect'; location: string; reason: string; clearCookies?: boolean }
70
- | { type: 'service_error'; reason: string }
75
+ | { type: 'service_error'; reason: string; check?: UnavailableCheck }
71
76
  | { type: 'refresh_needed' };
72
77
 
73
78
  // =============================================================================
@@ -135,29 +140,42 @@ export interface MvpMiddlewareOptions {
135
140
  */
136
141
  sessionResetRoute?: boolean | string;
137
142
  /**
138
- * PAY-1882 step 4 - how this app treats a producer that reports the session's
143
+ * PAY-1882 step 4 / PAY-2339 - how this app treats a producer that reports the session's
139
144
  * revocation status as `'unknown'` (a Vibe read that FAILED: non-OK, timeout,
140
145
  * throw - the status could not be determined).
141
146
  *
142
- * 'closed' (DEFAULT) - an unknown revocation status is NOT viable; the
143
- * session is force-invalidated and the user re-auths.
144
- * This is Jon's PAY-1880 ruling (option A, fail closed),
145
- * 2026-09-27, and BAPert 66316/66320 restates it for
146
- * step 4. Consequence, accepted explicitly: a Vibe
147
- * outage signs this app's users out. 'not_configured'
148
- * also fails closed here - both live consumers ARE
149
- * configured (BAPert 66356), so for them it means a
150
- * misconfiguration, not "no revocation source".
151
- * 'open' - an unknown OR not-configured status stays viable
152
- * (availability over fail-closed). Per-app opt-out for a
153
- * deployment with no revocation source, or the two live
154
- * consumers while Jon decides.
147
+ * 'hold' (DEFAULT since PAY-2339, Jon 2026-10-13, option C) - the member is NOT signed out. The request is
148
+ * answered "temporarily unavailable": a page goes to /service-unavailable?callbackUrl=
149
+ * (the session cookie is NOT touched, so "Try again" returns the member still signed in);
150
+ * an /api request gets a 503 carrying `unavailable: true` and `check: 'revocation'`, a
151
+ * fixed machine-readable value. Nothing protected is served while the answer is unknown.
152
+ * Each held request logs one countable `revocation_unavailable` line.
153
+ * THIS REPLACES THE OLD DEFAULT: the PAY-1880 ruling (Jon, 2026-09-27, option A) made
154
+ * 'closed' the default and accepted that a Vibe outage signs an app's users out. That
155
+ * sentence no longer applies to 'unknown' by default: a Vibe outage no longer signs members
156
+ * out unless the app asks for 'closed'. 'revoked' is unchanged.
157
+ * 'closed' - an unknown revocation status is NOT viable; the session is force-invalidated and the
158
+ * user re-auths (TODAY'S sign-out, now opt-in by name). Consequence, accepted explicitly:
159
+ * a Vibe outage signs this app's users out.
160
+ * 'open' - an unknown status stays viable (availability over fail-closed). Per-app opt-out for a
161
+ * deployment with no revocation source.
155
162
  *
156
- * Neither mode changes `'revoked'` (always force-invalid) or an ABSENT
157
- * `revocationStatus` (an older producer - unchanged behaviour, so no consumer
158
- * is signed out for not implementing the check).
163
+ * `'not_configured'` is UNCHANGED under the default: it is a configuration fault, not an outage, so it still
164
+ * force-invalidates exactly as before (a "try again" page would be false); `noRevocationSource` is the only way
165
+ * to make it viable. Neither mode changes `'revoked'` (always force-invalid, unchanged) or an ABSENT
166
+ * `revocationStatus` (an older producer - unchanged behaviour, so no consumer is signed out for not
167
+ * implementing the check). A consumer that wrote 'closed' or 'open' by name keeps exactly what it asked for.
168
+ */
169
+ revocationFailMode?: 'hold' | 'closed' | 'open';
170
+
171
+ /**
172
+ * PAY-2339 (BAPert 74640): where a page request goes while a revocation answer is held. DEFAULT (absent): the
173
+ * middleware answers inline with a minimal 503 HTML page ("Temporarily unavailable", a "Try again" link to the safe
174
+ * callback, no Set-Cookie), so a consumer that never added a page cannot get a 404. Name a same-site path (e.g.
175
+ * '/service-unavailable') to redirect there instead with `?callbackUrl=`; the consumer then mounts
176
+ * `export { default } from '@payez/next-mvp/pages/service-unavailable'` (or its own page) at that route.
159
177
  */
160
- revocationFailMode?: 'closed' | 'open';
178
+ unavailablePage?: string;
161
179
 
162
180
  /**
163
181
  * PAY-2302 cut 1c (BAPert 73585): this app has NO revocation source - for example a development environment
@@ -353,13 +371,34 @@ async function refreshFailureResponse(
353
371
  * requested path as `callbackUrl` so "Try again" returns the user to it still signed in. The path goes
354
372
  * through safeCallbackPath (URL-parser origin check): an off-origin or auth-surface value is dropped.
355
373
  */
356
- function serviceUnavailableResponse(request: NextRequest): NextResponse {
374
+ function serviceUnavailableResponse(request: NextRequest, check: UnavailableCheck = 'viability', unavailablePage?: string): NextResponse {
357
375
  const { pathname, search } = request.nextUrl;
358
376
  if (pathname.startsWith('/api/')) {
359
- return NextResponse.json({ error: 'ServiceUnavailable' }, { status: 503 });
377
+ // PAY-2339 P1/P12: one fixed machine-readable shape for every "could not check" answer. No protected data.
378
+ return NextResponse.json({ error: 'ServiceUnavailable', unavailable: true, check }, { status: 503 });
360
379
  }
361
- const target = new URL('/service-unavailable', request.url);
362
380
  const callback = safeCallbackPath(pathname + search);
381
+ // PAY-2339 (BAPert 74640, P13): a HELD revocation answer needs no page in the consumer. Unless the app names its own
382
+ // page (`unavailablePage`), the middleware answers inline: a minimal 503 HTML, a "try again" link to the safe
383
+ // callback, and no Set-Cookie (nothing here touches the session). No redirect, so no 404 is possible.
384
+ // `unavailablePage` is accepted only as a PLAIN path ([A-Za-z0-9_-/]; no query, fragment, %-encoding, dot segment or
385
+ // scheme), so the self-check below compares like with like and a mis-set value falls back to the inline page (Scout 74668).
386
+ // The named page applies to the revocation hold ONLY (BAPert 74648: the viability-failure arm is untouched). If the
387
+ // request is already FOR the named page (an app that did not register it as public), answer inline: redirecting to
388
+ // it again would loop with a longer callbackUrl each time (QAPert 74651).
389
+ const named = check === 'revocation' && unavailablePage && /^\/[A-Za-z0-9_\-\/]*$/.test(unavailablePage) && !unavailablePage.includes('//') ? unavailablePage : null;
390
+ if (check === 'revocation' && (!named || pathname.replace(/\/+$/, '') === named.replace(/\/+$/, ''))) {
391
+ const href = callback.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
392
+ return new NextResponse(
393
+ '<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Temporarily unavailable</title>' +
394
+ '<main role="status" style="font-family:system-ui,sans-serif;max-width:28rem;margin:20vh auto;padding:0 1rem;text-align:center">' +
395
+ '<h1 style="font-size:1.25rem">Temporarily unavailable</h1>' +
396
+ '<p>We could not check your session just now. You are still signed in.</p>' +
397
+ '<p><a href="' + href + '">Try again</a></p></main>',
398
+ { status: 503, headers: { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'retry-after': '30' } },
399
+ );
400
+ }
401
+ const target = new URL(named || '/service-unavailable', request.url);
363
402
  if (callback !== '/') target.searchParams.set('callbackUrl', callback);
364
403
  return NextResponse.redirect(target);
365
404
  }
@@ -438,6 +477,14 @@ function makeAuthDecision(ctx: AuthContext): AuthAction {
438
477
  return { type: 'service_error', reason: 'viability_check_failed' };
439
478
  }
440
479
 
480
+ // --- PAY-2339: the revocation backend could not answer and this app HOLDS (the default) ---
481
+ // Not a verdict on the session: no cookie is touched, nothing protected is served, and the answer says why in a
482
+ // fixed machine-readable form. The login page stays reachable.
483
+ if (sessionStatus.unavailable) {
484
+ if (onLoginPage) return { type: 'allow' };
485
+ return { type: 'service_error', reason: 'revocation_unknown', check: 'revocation' };
486
+ }
487
+
441
488
  // --- Session force-invalidated (admin action, password change, etc.) ---
442
489
  if (sessionStatus.forceInvalid) {
443
490
  if (onLoginPage) return { type: 'allow' };
@@ -557,8 +604,9 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
557
604
  const refreshEndpoint = options.refreshEndpoint || '/api/auth/refresh';
558
605
  const bypassPaths = options.bypassPaths || [];
559
606
  const rbacExemptPaths = options.rbacExemptPaths || [];
560
- // PAY-1882 step 4: default 'closed' (Jon's option A / BAPert 66316).
561
- const revocationFailMode = options.revocationFailMode || 'closed';
607
+ // PAY-2339: the default is 'hold' (Jon 2026-10-13, option C): an unknown revocation answer does not sign the member
608
+ // out. PAY-1882 step 4 had 'closed' (Jon's PAY-1880 option A, BAPert 66316); it is now opt-in by name.
609
+ const revocationFailMode = options.revocationFailMode || 'hold';
562
610
  // PAY-2302 cut 1c: strictly `=== true`, so a truthy string in a config file cannot switch revocation off.
563
611
  const noRevocationSource = options.noRevocationSource === true;
564
612
  if (noRevocationSource) {
@@ -693,6 +741,7 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
693
741
  refreshEndpoint,
694
742
  rbacExemptPaths,
695
743
  reset: resolveReset(),
744
+ unavailablePage: options.unavailablePage,
696
745
  onRefreshSuccess: options.onRefreshSuccess,
697
746
  onRefreshFailure: options.onRefreshFailure,
698
747
  });
@@ -711,26 +760,44 @@ export function createMvpMiddleware(options: MvpMiddlewareOptions = {}) {
711
760
  * 'unknown'/'not_configured'. The booleans are read ONLY when revocationStatus is
712
761
  * absent (idealresume.online's older boolean-only route).
713
762
  */
714
- export function decideForceInvalid(
763
+ export type RevocationOutcome = 'viable' | 'invalid' | 'hold';
764
+
765
+ /**
766
+ * PAY-2339: the three-way form of the revocation decision. `decideForceInvalid` below is kept as its boolean view.
767
+ *
768
+ * 'invalid' - sign the member out (cookies cleared, login page)
769
+ * 'hold' - the backend could not answer and this app holds: no sign-out, answer "temporarily unavailable"
770
+ * 'viable' - carry on
771
+ */
772
+ export function decideRevocationOutcome(
715
773
  data: { revocationStatus?: unknown; forceInvalid?: unknown; revoked?: unknown },
716
- revocationFailMode: 'closed' | 'open',
774
+ revocationFailMode: 'hold' | 'closed' | 'open',
717
775
  noRevocationSource: boolean = false,
718
- ): boolean {
776
+ ): RevocationOutcome {
719
777
  const status = data.revocationStatus;
720
778
  if (typeof status === 'string') {
721
- if (status === 'revoked') return true;
722
- if (status === 'active') return false;
779
+ if (status === 'revoked') return 'invalid';
780
+ if (status === 'active') return 'viable';
723
781
  // PAY-2302 cut 1c: an app that declared it has no revocation source. ONLY the exact 'not_configured' string.
724
- if (status === 'not_configured' && noRevocationSource === true) return false;
725
- // S1 (NightHawk 66409): ANY other string - 'unknown', 'not_configured', a
726
- // typo like 'Revoked', 'error', or '' - is treated as 'unknown' (fail mode
727
- // applies), NEVER as 'active'. Returning false here would let the first
728
- // producer that emits an unexpected state silently switch revocation OFF -
729
- // the exact PAY-1880 fail-open class. Only an explicit 'active' is viable.
730
- return revocationFailMode === 'closed';
782
+ if (status === 'not_configured' && noRevocationSource === true) return 'viable';
783
+ // PAY-2339: 'not_configured' is a configuration fault, not an outage. Under the default it stays signed out
784
+ // exactly as before; only 'open' relaxes it (a Vibe-less app).
785
+ if (status === 'not_configured') return revocationFailMode === 'open' ? 'viable' : 'invalid';
786
+ // S1 (NightHawk 66409): ANY other string - 'unknown', a typo like 'Revoked', 'error', or '' - is treated as
787
+ // 'unknown' (the fail mode applies), NEVER as 'active'. Only an explicit 'active' is viable.
788
+ if (revocationFailMode === 'open') return 'viable';
789
+ return revocationFailMode === 'closed' ? 'invalid' : 'hold';
731
790
  }
732
- // No revocationStatus: an older boolean producer. Absence of both stays false.
733
- return data.forceInvalid === true || data.revoked === true;
791
+ // No revocationStatus: an older boolean producer. Absence of both stays viable.
792
+ return data.forceInvalid === true || data.revoked === true ? 'invalid' : 'viable';
793
+ }
794
+
795
+ export function decideForceInvalid(
796
+ data: { revocationStatus?: unknown; forceInvalid?: unknown; revoked?: unknown },
797
+ revocationFailMode: 'hold' | 'closed' | 'open',
798
+ noRevocationSource: boolean = false,
799
+ ): boolean {
800
+ return decideRevocationOutcome(data, revocationFailMode, noRevocationSource) === 'invalid';
734
801
  }
735
802
 
736
803
  /**
@@ -750,7 +817,7 @@ async function checkViability(
750
817
  request: NextRequest,
751
818
  endpoint: string,
752
819
  log: MiddlewareLogger,
753
- revocationFailMode: 'closed' | 'open',
820
+ revocationFailMode: 'hold' | 'closed' | 'open',
754
821
  noRevocationSource: boolean = false
755
822
  ): Promise<{
756
823
  sessionStatus: SessionStatus;
@@ -829,7 +896,13 @@ async function checkViability(
829
896
  // revocations status, decide from it + failMode and ignore the folded
830
897
  // booleans for unknown/not_configured. The booleans are read ONLY when
831
898
  // revocationStatus is ABSENT (idealresume.online's older boolean route).
832
- sessionStatus.forceInvalid = decideForceInvalid(data, revocationFailMode, noRevocationSource);
899
+ const outcome = decideRevocationOutcome(data, revocationFailMode, noRevocationSource);
900
+ sessionStatus.forceInvalid = outcome === 'invalid';
901
+ if (outcome === 'hold') {
902
+ sessionStatus.unavailable = true;
903
+ // PAY-2339 P11: one countable line per held request, naming the check. No session value, no address.
904
+ log.warn('revocation_unavailable', { check: 'revocation' });
905
+ }
833
906
  // PAY-2216: a STALE session - the cookie resolved to a token, but no store holds the session - used to set
834
907
  // pointer.exists=false, so makeAuthDecision took no_session (login, cookie NOT cleared) and its stale_session
835
908
  // arm (clearCookies) was unreachable: a dead cookie lingered and re-ran viability on every request.
@@ -869,6 +942,8 @@ interface ExecuteOptions {
869
942
  rbacExemptPaths: string[];
870
943
  /** PAY-2218: set when the app mounted the session-reset route AND a signing secret exists. */
871
944
  reset?: ResetConfig;
945
+ /** PAY-2339: the app's named hold page; absent = the inline 503 HTML. */
946
+ unavailablePage?: string;
872
947
  onRefreshSuccess?: () => void;
873
948
  onRefreshFailure?: (status: number, isNetworkError: boolean) => void;
874
949
  }
@@ -894,7 +969,7 @@ async function executeDecision(
894
969
  : redirectTo(request, decision.location);
895
970
 
896
971
  case 'service_error':
897
- return serviceUnavailableResponse(request);
972
+ return serviceUnavailableResponse(request, decision.check ?? 'viability', opts.unavailablePage);
898
973
 
899
974
  case 'refresh_needed':
900
975
  // PAY-2136: a speculative request must not spend (rotate) a single-use refresh token or, on a 401/403,
@@ -0,0 +1,63 @@
1
+ 'use client';
2
+
3
+ import React, { Suspense } from 'react';
4
+ import { useSearchParams } from 'next/navigation';
5
+
6
+ /**
7
+ * PAY-2339 (option C): the default "temporarily unavailable" page the middleware sends a member to when the revocation
8
+ * check (or the viability read) could not answer. Mount it in one line in the consuming app:
9
+ *
10
+ * // app/service-unavailable/page.tsx
11
+ * export { default } from '@payez/next-mvp/pages/service-unavailable';
12
+ *
13
+ * It signs nobody out and clears nothing: "Try again" goes back to `callbackUrl`, and the member is still signed in. A
14
+ * consumer may replace the page (and the wording) with its own at the same route.
15
+ *
16
+ * `callbackUrl` is untrusted input. Only a same-origin PATH is followed ("/dashboard"); anything else (an absolute URL,
17
+ * a protocol-relative "//host", a "javascript:" value, a backslash trick, nothing at all) falls back to "/".
18
+ */
19
+ export function safeReturnPath(raw: string | null | undefined): string {
20
+ if (!raw || typeof raw !== 'string') return '/';
21
+ if (!raw.startsWith('/') || raw.startsWith('//') || raw.includes('\\')) return '/';
22
+ if (/[\u0000-\u001f]/.test(raw)) return '/';
23
+ return raw;
24
+ }
25
+
26
+ function ServiceUnavailableContent() {
27
+ const params = useSearchParams();
28
+ const back = safeReturnPath(params?.get('callbackUrl'));
29
+ return (
30
+ <div className="min-h-screen flex items-center justify-center p-4">
31
+ <div
32
+ role="status"
33
+ className="max-w-md w-full text-center rounded-xl p-8 shadow-lg border"
34
+ style={{
35
+ backgroundColor: 'var(--bg-card, #ffffff)',
36
+ borderColor: 'var(--border-default, #e5e7eb)',
37
+ }}
38
+ >
39
+ <h1 className="text-xl font-semibold mb-2" style={{ color: 'var(--text-primary, #111827)' }}>
40
+ Temporarily unavailable
41
+ </h1>
42
+ <p className="mb-6" style={{ color: 'var(--text-secondary, #6b7280)' }}>
43
+ We could not check your session just now. You are still signed in. Please try again in a moment.
44
+ </p>
45
+ <a
46
+ href={back}
47
+ className="inline-block rounded-lg px-4 py-2 font-medium"
48
+ style={{ background: 'var(--color-primary, #10b981)', color: 'white' }}
49
+ >
50
+ Try again
51
+ </a>
52
+ </div>
53
+ </div>
54
+ );
55
+ }
56
+
57
+ export default function ServiceUnavailablePage() {
58
+ return (
59
+ <Suspense fallback={null}>
60
+ <ServiceUnavailableContent />
61
+ </Suspense>
62
+ );
63
+ }
@@ -14,6 +14,7 @@
14
14
  * @since auth-ready-v2
15
15
  */
16
16
 
17
+ import { revocationFields } from '../../auth/revocation-fields';
17
18
  import { NextRequest, NextResponse } from 'next/server';
18
19
  import { resolveSessionState } from '../../server/auth';
19
20
  import {
@@ -157,6 +158,7 @@ export async function GET(req: NextRequest) {
157
158
  needsRefresh: false,
158
159
  authenticated: false,
159
160
  revocationStatus: 'unknown' as RevocationStatus,
161
+ unavailable: true, // PAY-2339: a reader of this JSON gets the hold signal (the response is non-OK, so the middleware holds as service_error)
160
162
  error: 'Session store unavailable',
161
163
  code: 'STORE_UNAVAILABLE'
162
164
  }, { status: 500 });
@@ -383,8 +385,7 @@ export async function GET(req: NextRequest) {
383
385
  // Session revocation (PAY-1882 step 4): the four-state status, plus the
384
386
  // boolean the middleware's existing force-invalid branch already reads.
385
387
  revocationStatus,
386
- forceInvalid: revocationStatus === 'revoked' || revocationStatus === 'unknown',
387
- revoked: revocationStatus === 'revoked',
388
+ ...revocationFields(revocationStatus), // PAY-2339: forceInvalid only for 'revoked'; unavailable:true for 'unknown'
388
389
  // Clear names for middleware decision-making
389
390
  tenantRequiresTwoFactor,
390
391
  userHasCompletedTenantTwoFactorRequirements,
@@ -468,8 +469,7 @@ export async function GET(req: NextRequest) {
468
469
  reason: 'Token expired',
469
470
  // Session revocation (PAY-1882 step 4) - same value on every return.
470
471
  revocationStatus,
471
- forceInvalid: revocationStatus === 'revoked' || revocationStatus === 'unknown',
472
- revoked: revocationStatus === 'revoked',
472
+ ...revocationFields(revocationStatus), // PAY-2339: forceInvalid only for 'revoked'; unavailable:true for 'unknown'
473
473
  // RBAC fields
474
474
  roles: session?.roles || [],
475
475
  clientId: resolveClientId(session?.idpClientId),
@@ -485,8 +485,7 @@ export async function GET(req: NextRequest) {
485
485
  sessionTokenId: sessionToken ? tokenLogId(sessionToken) : null,
486
486
  // Session revocation (PAY-1882 step 4) - same value on every return.
487
487
  revocationStatus,
488
- forceInvalid: revocationStatus === 'revoked' || revocationStatus === 'unknown',
489
- revoked: revocationStatus === 'revoked',
488
+ ...revocationFields(revocationStatus), // PAY-2339: forceInvalid only for 'revoked'; unavailable:true for 'unknown'
490
489
  // Clear names
491
490
  tenantRequiresTwoFactor,
492
491
  userHasCompletedTenantTwoFactorRequirements,
package/src/types/auth.ts CHANGED
@@ -25,6 +25,12 @@ export interface AuthConfig {
25
25
  * An OAuth-only client is a deliberate choice, never the default.
26
26
  */
27
27
  allowTraditionalLogin?: boolean;
28
+ /**
29
+ * PAY-2334: where /api/auth/settings stands. 'loading' = not answered yet, 'ready' = answered (or nothing to ask:
30
+ * useDynamicProviders off), 'failed' = non-2xx, thrown, or timed out. Absent means 'ready'. A page must not tell the user
31
+ * "sign-in is not available" while this is 'loading', and must say a failed read is a failed read, not an empty answer.
32
+ */
33
+ settingsStatus?: 'loading' | 'ready' | 'failed';
28
34
  providers: FederatedProvider[];
29
35
  enableRecovery: boolean;
30
36
  enableEmailSignup: boolean;