parity(api,apps): security hotfix stage 2 - real customer sessions, close IDOR

Stage 1 narrowed GET /customers but did not close the leak: the response still
carried every customer id, and /customers/:id, /:id/orders and
/:id/ledger-entries were still public, so the full customer book was still two
requests away. The user caught this. Stage 2 deletes the id-bearing surface.

Customer JWT, separate from the admin one (T1):
  - new src/modules/customer-auth/ with its own passport strategy,
    CustomerJwtGuard, @CustomerAuth() and @CurrentCustomer()
  - signed with JWT_CUSTOMER_SECRET, and every token carries typ:'customer'
    which the strategy verifies; both checks are present deliberately
  - customer state re-read per request, so deactivating takes effect at once
  - mirrors the reference's own split: auth:api vs auth('api-customer')

Real OTP (D6), porting ApiMobileController::userAuth/userVerfiy (:39-64):
  - new CustomerOtp table, additive migration, nothing existing touched
  - parity behaviour: rand(1000,9999), active-customer filter, faTOen digit
    normalisation on both number and code, rejection on mismatch
  - approved improvements over the reference: bcrypt-hashed code, 2-minute
    expiry, 5 attempts then lockout, single use, send throttle (60s per
    number, 5/number and 20/IP per 10 min), and no number enumeration

Routes removed, replaced by token-derived equivalents:
  GET customers, customers/:id, /:id/orders, /:id/ledger-entries
    -> GET customer/me, customer/me/orders, customer/me/ledger-entries
No route accepts a customer id any more, so the IDOR is closed structurally
rather than by a check. The admin panel was unaffected (admin/customers-omde/*).

Both apps migrated in the same commit per the v1/v2 parity rule: token-based
session store, Bearer header, 401 -> clear session and route to login, real
two-step OTP login. Each app keeps its own markup and styling; only logic moved.

Tests: auth-smoke.sh extended with the stage-2 assertions, 46 passed 0 failed
against a live server. jest installed dev-only (user-approved) so pnpm test
works for the first time: 7 passed covering faToEn, which moved to its own
digits.ts to be testable without booting Nest. Typecheck clean on api,
user-app and user-app-v2; both apps build.

[ref: henza_server ApiMobileController.php:39-78]

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
s.esmaeili
2026-09-22 01:20:00 +03:30
co-authored by Claude Opus 5
parent fdf833565f
commit 4efe543d62
42 changed files with 3552 additions and 277 deletions
+76 -25
View File
@@ -1,12 +1,56 @@
import type { CreateOrderDto, CustomerBalanceDto } from '@gold-bank/shared-types';
import type { CreateOrderDto } from '@gold-bank/shared-types';
const BASE = '/api';
const TOKEN_KEY = 'gold-bank:token';
/**
* Called when the API rejects our token. Wired up in main.ts rather than
* imported from the store, so this module stays free of a Pinia dependency
* (the client is used before Pinia is active during app bootstrap).
*/
let onUnauthorized: (() => void) | null = null;
export function setUnauthorizedHandler(fn: () => void) {
onUnauthorized = fn;
}
/** Thrown for a 401 so callers can tell "session gone" from any other failure. */
export class UnauthorizedError extends Error {
constructor(path: string) {
super(`API ${path} rejected the session (401)`);
this.name = 'UnauthorizedError';
}
}
function readToken(): string | null {
try {
return localStorage.getItem(TOKEN_KEY);
} catch {
// Private mode / blocked storage — treat as logged out rather than throwing.
return null;
}
}
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const token = readToken();
const res = await fetch(`${BASE}${path}`, {
headers: { 'Content-Type': 'application/json' },
...options,
headers: {
'Content-Type': 'application/json',
// Customer JWT from POST /customer/auth/verify-otp. The API derives the
// customer from this, never from an id in the URL.
...(token ? { Authorization: `Bearer ${token}` } : {}),
...options?.headers,
},
});
if (res.status === 401) {
// Expired or revoked: drop the session and send the user to login, so no
// stale personal data stays on screen behind a dead token.
onUnauthorized?.();
throw new UnauthorizedError(path);
}
if (!res.ok) {
const body = await res.text();
throw new Error(`API ${path} failed (${res.status}): ${body}`);
@@ -85,24 +129,6 @@ export interface LedgerEntrySummary {
note: string | null;
}
/**
* What `GET /customers` returns — the login lookup, and nothing more.
*
* It used to carry fullName, national ID, both debts and the credit limit. The
* route is unauthenticated (the login screen matches the phone number in the
* browser), so that shipped the whole customer book to any visitor; the API now
* selects only these four fields. See SEC-08 in docs/parity/ISSUES.md.
*
* The route disappears altogether once OTP verify returns the one authenticated
* customer, the way the reference did it.
*/
export interface CustomerSummary {
id: string;
mobile: string;
isActive: boolean;
isArchived: boolean;
}
export interface OrderSummary {
id: string;
orderNumber: string;
@@ -165,12 +191,37 @@ export interface AdminSlide {
export const api = {
listProducts: () => request<ProductSummary[]>('/catalog/products'),
listCustomers: () => request<CustomerSummary[]>('/customers'),
getCustomer: (id: string) => request<CustomerDetail>(`/customers/${id}`),
getBalance: (customerId: string) => request<CustomerBalanceDto>(`/accounting/customers/${customerId}/balance`),
getLedgerEntries: (customerId: string) => request<LedgerEntrySummary[]>(`/customers/${customerId}/ledger-entries`),
/**
* Step 1 of login — ports henza_server ApiMobileController::userAuth.
* Always resolves `{ sent: true }`, even for an unregistered number, so the
* endpoint cannot be used to discover which numbers are customers.
*/
requestOtp: (username: string) =>
request<{ sent: boolean }>('/customer/auth/request-otp', {
method: 'POST',
body: JSON.stringify({ username }),
}),
/**
* Step 2 — ports ApiMobileController::userVerfiy. The server compares the
* code and returns a token plus that one customer. A wrong, expired or
* already-used code is a 401.
*/
verifyOtp: (username: string, password: string) =>
request<{ token: string; customer: { id: string; mobile: string } }>(
'/customer/auth/verify-otp',
{ method: 'POST', body: JSON.stringify({ username, password }) },
),
// The three reads below identify the customer by TOKEN. They replaced
// /customers/:id, /:id/orders and /:id/ledger-entries, which took the id from
// the URL and let anyone read anyone (SEC-08).
getMe: () => request<CustomerDetail>('/customer/me'),
getMyOrders: () => request<OrderDetail[]>('/customer/me/orders'),
getMyLedgerEntries: () => request<LedgerEntrySummary[]>('/customer/me/ledger-entries'),
createOrder: (dto: CreateOrderDto) => request<OrderSummary>('/orders', { method: 'POST', body: JSON.stringify(dto) }),
getCustomerOrders: (customerId: string) => request<OrderDetail[]>(`/customers/${customerId}/orders`),
getLatestGoldPrice: (karatPerMille = 750) => request<GoldPriceQuote>(`/pricing/latest?karatPerMille=${karatPerMille}`),
/** GET /home/slider — public, no auth. Empty array when the admin hasn't
* configured any slides (the caller falls back to a derived hero). */
+12
View File
@@ -3,6 +3,8 @@ import { createPinia } from 'pinia';
import VueLazyLoad from 'vue3-lazyload';
import App from './App.vue';
import { router } from './router';
import { setUnauthorizedHandler } from './api/client';
import { useSessionStore } from './stores/session';
import Container from './components/ui/Container.vue';
// TODO: temporary placeholder — swap Vector.svg back in (or a proper loading
// mark) once one exists; montzar-logo.png is the brand logo, borrowed here
@@ -21,6 +23,16 @@ const app = createApp(App);
app.use(createPinia());
app.use(router);
// A 401 from the API means the customer token is gone or expired. Clear the
// session and send the user to login, so no stale personal data stays on
// screen behind a dead token. Registered after Pinia so the store exists.
setUnauthorizedHandler(() => {
useSessionStore().logout();
if (router.currentRoute.value.name !== 'login') {
void router.push({ name: 'login' });
}
});
// Ported from legacy main.ts:32-46 — Vector.svg is both the while-loading and
// the on-error placeholder, so a missing/failed image paints the brand mark
// instead of collapsing the layout.
+2 -2
View File
@@ -53,10 +53,10 @@ router.beforeEach((to) => {
const session = useSessionStore();
const nav = useNavStore();
if (to.name === 'login' && session.customerId) {
if (to.name === 'login' && session.isLoggedIn) {
return { name: 'home' };
}
if (to.meta.requiresAuth && !session.customerId) {
if (to.meta.requiresAuth && !session.isLoggedIn) {
return { name: 'login', query: { redirect: to.fullPath } };
}
+41 -18
View File
@@ -1,35 +1,58 @@
import { defineStore } from 'pinia';
const TOKEN_KEY = 'gold-bank:token';
const CUSTOMER_ID_KEY = 'gold-bank:customerId';
const MOBILE_KEY = 'gold-bank:mobile';
/** Legacy's isUserLoggedIn() (Mixins/checkAccess.ts) reads this key. */
const LEGACY_FLAG_KEY = 'appToken';
/**
* Holds the logged-in customer's identity. Now backed by a real (if stubbed —
* see LoginView.vue) login flow: `login()` sets the same `appToken`
* localStorage key legacy's `isUserLoggedIn()` reads, so downstream login
* gates keep working unchanged.
* The logged-in customer's session.
*
* `token` is the credential. It is a real customer JWT issued by
* POST /api/customer/auth/verify-otp after the SMS code is checked server-side,
* and it is what every /customer/me* request is authorised with.
*
* `customerId` is kept for display and for cart bookkeeping only — it is NOT an
* identity claim any more. Until the OTP migration, the app sent this id in the
* URL of /customers/:id and the server trusted it, which meant anyone could
* read anyone's profile, orders and ledger by changing the value. The API no
* longer has an id-bearing customer route at all; the server derives the
* customer from the token. See SEC-08 in docs/parity/ISSUES.md.
*/
export const useSessionStore = defineStore('session', {
state: () => ({
customerId: localStorage.getItem('gold-bank:customerId') as string | null,
mobile: localStorage.getItem('gold-bank:mobile') as string | null,
token: localStorage.getItem(TOKEN_KEY) as string | null,
customerId: localStorage.getItem(CUSTOMER_ID_KEY) as string | null,
mobile: localStorage.getItem(MOBILE_KEY) as string | null,
}),
getters: {
/** Authenticated means holding a token, not merely knowing an id. */
isLoggedIn: (state) => Boolean(state.token),
},
actions: {
setCustomerId(id: string) {
this.customerId = id;
localStorage.setItem('gold-bank:customerId', id);
},
login(customerId: string, mobile: string) {
login(token: string, customerId: string, mobile: string) {
this.token = token;
this.customerId = customerId;
this.mobile = mobile;
localStorage.setItem('gold-bank:customerId', customerId);
localStorage.setItem('gold-bank:mobile', mobile);
// matches legacy's isUserLoggedIn() check (Mixins/checkAccess.ts)
localStorage.setItem('appToken', customerId);
localStorage.setItem(TOKEN_KEY, token);
localStorage.setItem(CUSTOMER_ID_KEY, customerId);
localStorage.setItem(MOBILE_KEY, mobile);
localStorage.setItem(LEGACY_FLAG_KEY, token);
},
/**
* Clears everything. Called on explicit logout and by the API client when a
* request comes back 401 — an expired or revoked token must not leave stale
* personal data on screen.
*/
logout() {
this.token = null;
this.customerId = null;
this.mobile = null;
localStorage.removeItem('gold-bank:customerId');
localStorage.removeItem('gold-bank:mobile');
localStorage.removeItem('appToken');
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(CUSTOMER_ID_KEY);
localStorage.removeItem(MOBILE_KEY);
localStorage.removeItem(LEGACY_FLAG_KEY);
},
},
});
@@ -36,7 +36,7 @@
<span class="dash__barSpacer" aria-hidden="true" />
<h1 class="dash__barTitle">میز کار</h1>
<button
v-if="session.customerId"
v-if="session.isLoggedIn"
type="button"
class="dash__barBtn"
aria-label="خروج"
@@ -189,7 +189,7 @@ const list = [
]
function goToDetails(id: number) {
if (!session.customerId) {
if (!session.isLoggedIn) {
data.loginNotify = true
return
}
@@ -206,8 +206,8 @@ function logOut() {
}
async function loadDashboard() {
if (session.customerId) {
customer.value = await api.getCustomer(session.customerId)
if (session.isLoggedIn) {
customer.value = await api.getMe()
}
try {
goldPrice.value = await api.getLatestGoldPrice()
+49 -24
View File
@@ -92,7 +92,7 @@ import NotifyVant from '../../components/NotifyVant.vue'
import OtpInput from '../../components/input/OtpInput.vue'
import { required, mobile as mobileRule } from '../../utils/validator'
import { useSessionStore } from '../../stores/session'
import { api, type CustomerSummary } from '../../api/client'
import { api } from '../../api/client'
const emit = defineEmits<{ (e: 'register', value: boolean): void }>()
const router = useRouter()
@@ -107,8 +107,6 @@ const body = reactive({
defaultFocus: false,
})
let matchedCustomer: CustomerSummary | null = null
const timer = ref(0)
const countDownTimer = () => {
if (timer.value > 0) {
@@ -121,52 +119,79 @@ const countDownTimer = () => {
}
}
/**
* Step 1 — ask the server to send an SMS code.
*
* This used to download every customer via GET /customers and match the phone
* number here in the browser, which handed any visitor the whole customer book
* (SEC-08). The lookup now happens server-side, exactly as the reference did it
* (henza_server ApiMobileController::userAuth, :39-49).
*
* The response is deliberately the same whether or not the number is
* registered, so an unknown number can no longer be told apart from a known
* one. That means we advance to step 2 either way; a number that does not exist
* simply never receives a code, and the verify call then rejects it.
*/
const sendPhone = async () => {
try {
body.loading = true
// GET /api/customers already filters to isActive && !isArchived (matching
// legacy henza_server's Customer::active()->where('is_archive', 0)), but
// the check is repeated here in case that ever changes upstream — an
// inactive/archived customer must never be able to log in.
const customers = await api.listCustomers()
matchedCustomer =
customers.find((c) => c.mobile === formModel.username && c.isActive && !c.isArchived) ?? null
if (!matchedCustomer) {
notify.text = 'اطلاعات کاربری در سیستم وجود ندارد.'
notify.show = true
return
}
await api.requestOtp(String(formModel.username ?? ''))
body.step = 2
timer.value = 120
countDownTimer()
await nextTick(() => {
body.defaultFocus = true
})
} catch (e) {
console.log(e)
} catch (e: unknown) {
// 429 = the send throttle (too soon, or too many in the window). Its message
// is already Persian and user-facing, so show it rather than a generic one.
const text = e instanceof Error && /\(429\)/.test(e.message) ? extractServerMessage(e) : null
notify.text = text ?? 'خطا در ارسال کد. لطفاً دوباره تلاش کنید.'
notify.show = true
} finally {
body.loading = false
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const sendToken = async (_otpCode: string) => {
// Stub: the OTP code itself isn't verified (no SMS was actually sent to
// check it against). `matchedCustomer` was already confirmed real in
// sendPhone(), so any 4-digit code here logs in as that customer.
/**
* Step 2 — submit the code.
*
* The server compares it (reference: ApiMobileController::userVerfiy, :51-57,
* which aborts 422 on a mismatch) and returns a real token plus that one
* customer. Previously any 4-digit code was accepted client-side.
*/
const sendToken = async (otpCode: string) => {
try {
body.loading = true
if (!matchedCustomer) return
session.login(matchedCustomer.id, matchedCustomer.mobile)
const { token, customer } = await api.verifyOtp(String(formModel.username ?? ''), otpCode)
session.login(token, customer.id, customer.mobile)
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : undefined
await router.push(redirect ?? { name: 'home' })
notify.text = 'با موفقیت وارد شدید'
notify.show = true
} catch (e: unknown) {
notify.text =
e instanceof Error && /\(429\)/.test(e.message)
? (extractServerMessage(e) ?? 'تعداد تلاش‌ها بیش از حد مجاز است.')
: 'کد وارد شده صحیح نیست'
notify.show = true
} finally {
body.loading = false
}
}
/** Pulls the API's Persian `message` out of the thrown error's body text. */
function extractServerMessage(e: Error): string | null {
const match = e.message.match(/\{.*\}/)
if (!match) return null
try {
const parsed = JSON.parse(match[0]) as { message?: string }
return typeof parsed.message === 'string' ? parsed.message : null
} catch {
return null
}
}
const counterZeroShow = (value: number) => (value < 10 ? '0' + value : value)
const btnText = computed(() => (body.step === 1 ? 'دریافت رمز عبور' : 'دریافت مجدد رمز عبور'))
+2 -2
View File
@@ -194,10 +194,10 @@ function readSearch(value: string | undefined) {
}
async function loadOrders() {
if (!session.customerId) return
if (!session.isLoggedIn) return
loading.value = true
try {
allOrders.value = await api.getCustomerOrders(session.customerId)
allOrders.value = await api.getMyOrders()
} finally {
loading.value = false
}
+2 -2
View File
@@ -86,10 +86,10 @@ const loading = ref(false)
const isVerified = computed(() => customer.value?.verificationStep === 'VERIFIED')
onMounted(async () => {
if (!session.customerId) return
if (!session.isLoggedIn) return
loading.value = true
try {
customer.value = await api.getCustomer(session.customerId)
customer.value = await api.getMe()
} finally {
loading.value = false
}
@@ -140,10 +140,10 @@ const openEntry = (item: LedgerEntrySummary) => {
}
onMounted(async () => {
if (!session.customerId) return
if (!session.isLoggedIn) return
loading.value = true
try {
entries.value = await api.getLedgerEntries(session.customerId)
entries.value = await api.getMyLedgerEntries()
} finally {
loading.value = false
}