refactor(pl24): oturum modeli — tek login, çerez tabanlı authorize yenileme
Some checks are pending
QA Gate (P0/P1) / Test affected app (pull_request) Waiting to run

Faz 1 / adım 1 (analiz: /home/s/ss/plv2.md §4.1, bulgular auth-02/03/05/06/09/11/15,
p4legacy-07, consumers-04).

SORUN: PL24'ün base JWT'si 600 saniye yaşıyor ve kod bunu "oturum" sayıyordu
(isTokenValid → login). Talep varsa her ~9 dakikada bir squeezeOut:true ile
YENİDEN LOGIN atılıyordu (günde ~144 login/hesap). PL24 hesap başına tek oturum
veriyor; bu desen hem kendi oturumumuzu sürekli düşürüyor hem de iki hesap
banından önceki otomasyon imzasını oluşturuyordu. Portalın kendisi bir kez login
olup PL24TOKEN çerezini saklıyor ve yalnız authorize'ı yeniliyor.

DEĞİŞİKLİK:
- Oturum = PL24TOKEN çerezi (süresiz). `ensureSession()` sahibi; bellekte tutulur,
  Redis'te `pl24:auth:session:<hesap>` ile 24 saat paylaşılır (api/worker aynı
  oturumu devralır). Süre kontrolü YOK — oturum yalnız sunucu reddederse düşer.
- Servis token'ı = authorize ile mint edilen 600 s'lik JWT; yalnız `Cookie:
  PL24TOKEN` ile istenir (Bearer gerekmiyor — canlı doğrulandı).
- `session_status:"gone"` ve authorize 401/403 artık okunuyor: oturum düşürülür,
  tek sefer yeniden login + retry.
- Single-flight: süreç içi in-flight promise + Redis kilidi
  (`pl24:auth:login-lock:<hesap>`), kilidi alamayan paylaşılan oturumu bekler.
  Eski prewarm iki paralel login atıyordu ve biri her boot'ta HTTP 500 alıyordu.
- Login sözleşmesi: portal ucu `/auth/ext/api/1.1/login`
  ({account,user,password,squeezeOut} → {loginStatus,sessionToken} + Set-Cookie);
  RFC7807 problem gövdesi tiplendi. Önce squeezeOut:false denenir, yalnız
  "session-limit-exceeded"/USER_ALREADY_LOGGED_IN'de squeezeOut:true ile tekrar.
  `PL24_LOGIN_API=legacy` eski uca döner (bir sürüm geri çekilme bayrağı).
- Hata sınıflandırma: account-not-active / user-not-active / authentication /
  2FA-required → ilk hatada 6 saatlik devre kesici (eskiden ölü hesap 5 dakikada
  bir sonsuza dek deneniyordu: prod'da 376 ardışık 401). Ağ/timeout → 5 dakika.
- Saatlik login tavanı (hesap başına 6) — sağlıklı günde 0-1 login beklenir.
- P4 (.action) sayfaları için authorize kaldırıldı: yalnız çerez gönderiliyor
  (canlı doğrulandı). Ford/PSA'daki 18 "ısıtma" authorize çağrısı ensureSession'a
  indirildi; demo-sayfa/401 çaresi artık servis token temizleme değil oturum
  yenileme.
- Gerçek Chrome User-Agent sabiti (eski değer hiçbir tarayıcıda yok).
- authorize'a `pl24-wmidata` eklendi (portal WMI decode'u için ön hazırlık).
- Ölü kod silindi: getAccessToken*/getSessionCookie* base-JWT yolu, hasService,
  getAvailableServices, AUTH_TOKEN_TTL.

Test: pl24-auth.service.spec.ts yeniden yazıldı (19 test: tek login, single-flight,
Redis devralma, cookie-only authorize, gone/401 yeniden login, 412 squeezeOut,
P4 cookie-only header, kalıcı hata kesicisi, saatlik tavan). Tüm PL24 + tüketici
paketleri: 188 test geçti. tsc + biome temiz.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
semih
2026-09-17 00:59:36 +03:00
parent 330015fbb6
commit e50a907931
6 changed files with 898 additions and 507 deletions

View File

@@ -1,32 +1,101 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PL24AuthService } from "./pl24-auth.service";
// PL24_TR_DISABLED köprüsü + login devre kesici: ağ yok, login yolları global
// fetch stub'ıyla gözlenir; private durum repo genelindeki `as unknown as` kalıbıyla okunur.
// Oturum modeli (1 login → PL24TOKEN çerezi → yalnız authorize ile yenileme),
// PL24_TR_DISABLED köprüsü ve login devre kesici. Ağ yok: global fetch stub'ı;
// private durum repo genelindeki `as unknown as` kalıbıyla okunur.
const makeService = (cfgOverrides: Record<string, string> = {}) => {
type RedisStub = {
store: Map<string, unknown>;
getJson: (k: string) => Promise<unknown>;
setJson: (k: string, v: unknown) => Promise<void>;
del: (k: string) => Promise<void>;
setNx: (k: string, v: string, ttl: number) => Promise<boolean>;
incr: (k: string) => Promise<number>;
expire: (k: string, ttl: number) => Promise<void>;
};
const makeRedis = (opts: { lockTaken?: boolean } = {}): RedisStub => {
const store = new Map<string, unknown>();
const counters = new Map<string, number>();
return {
store,
getJson: async (k: string) => store.get(k) ?? null,
setJson: async (k: string, v: unknown) => {
store.set(k, v);
},
del: async (k: string) => {
store.delete(k);
},
setNx: async () => !opts.lockTaken,
incr: async (k: string) => {
const n = (counters.get(k) ?? 0) + 1;
counters.set(k, n);
return n;
},
expire: async () => {},
};
};
const makeService = (cfgOverrides: Record<string, string> = {}, redis = makeRedis()) => {
const cfg: Record<string, string> = {
"pl24.companyCode": "tr-903645",
"pl24.companyCode": "tr-000000",
"pl24.username": "admin",
"pl24.password": "pw-tr",
"pl24.companyCode2": "de-708171",
"pl24.companyCode2": "de-000000",
"pl24.username2": "admin",
"pl24.password2": "pw-de",
"pl24.proxyDe": "http://u:p@127.0.0.1:9",
...cfgOverrides,
};
const configService = { get: (k: string, d?: unknown) => cfg[k] ?? d } as never;
const redis = { getJson: async () => null, setJson: async () => {} } as never;
return new PL24AuthService(configService, redis);
return { svc: new PL24AuthService(configService, redis as never), redis };
};
type Exposed = {
effectiveAccount(account: "tr" | "de"): "tr" | "de";
login(forceNew?: boolean): Promise<unknown>;
login2(forceNew?: boolean): Promise<unknown>;
tokenData2: unknown;
login(account: "tr" | "de"): Promise<unknown>;
ensureSession(account: "tr" | "de"): Promise<{ sessionToken: string }>;
sessions: Record<string, { sessionToken: string } | undefined>;
serviceTokens: Record<"tr" | "de", Map<string, { token: string; expiresAt: number }>>;
};
/** Portal login yanıtı: {loginStatus, sessionToken} + Set-Cookie PL24TOKEN. */
const loginOk = (token = "sess-token-1") => ({
ok: true,
status: 200,
statusText: "OK",
headers: {
get: (h: string) => (h.toLowerCase() === "set-cookie" ? `PL24TOKEN=${token}; Path=/` : null),
getSetCookie: () => [`PL24TOKEN=${token}; Path=/; Secure`],
},
json: async () => ({ loginStatus: "OK", sessionToken: token }),
});
const jwt = (payload: Record<string, unknown>) =>
`h.${Buffer.from(JSON.stringify(payload)).toString("base64url")}.s`;
const authorizeOk = (scope = "vw_parts pl24-usage", sessionStatus = "alive") => ({
ok: true,
status: 200,
statusText: "OK",
headers: { get: () => null, getSetCookie: () => [] },
json: async () => ({
access_token: jwt({ exp: Math.floor(Date.now() / 1000) + 600, sid: "sess-token-1" }),
expires_in: 600,
scope,
session_status: sessionStatus,
}),
});
const problem = (status: number, type: string) => ({
ok: false,
status,
statusText: "Precondition Failed",
headers: { get: () => null, getSetCookie: () => [] },
json: async () => ({ type, title: type, detail: type }),
});
const savedFlag = process.env.PL24_TR_DISABLED;
beforeEach(() => {
@@ -41,40 +110,200 @@ afterEach(() => {
describe("PL24AuthService — PL24_TR_DISABLED tr→de köprüsü", () => {
it("bayrak kapalıyken hesaplar olduğu gibi kalır", () => {
const p = makeService() as unknown as Exposed;
const { svc } = makeService();
const p = svc as unknown as Exposed;
expect(p.effectiveAccount("tr")).toBe("tr");
expect(p.effectiveAccount("de")).toBe("de");
});
it("bayrak açıkken tr → de'ye maplenir, de değişmez", () => {
process.env.PL24_TR_DISABLED = "true";
const p = makeService() as unknown as Exposed;
const { svc } = makeService();
const p = svc as unknown as Exposed;
expect(p.effectiveAccount("tr")).toBe("de");
expect(p.effectiveAccount("de")).toBe("de");
});
it("de hesabı tanımlı değilse mapleme yapılmaz (duvara yönlendirme yok)", () => {
process.env.PL24_TR_DISABLED = "true";
const p = makeService({ "pl24.companyCode2": "" }) as unknown as Exposed;
expect(p.effectiveAccount("tr")).toBe("tr");
const { svc } = makeService({ "pl24.companyCode2": "" });
expect((svc as unknown as Exposed).effectiveAccount("tr")).toBe("tr");
});
it("bayrak açıkken tr login'i ağa çıkmadan reddedilir", async () => {
process.env.PL24_TR_DISABLED = "true";
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
const p = makeService() as unknown as Exposed;
await expect(p.login()).rejects.toThrow(/PL24_TR_DISABLED/);
const { svc } = makeService();
await expect((svc as unknown as Exposed).login("tr")).rejects.toThrow(/PL24_TR_DISABLED/);
expect(fetchSpy).not.toHaveBeenCalled();
});
it("legacy clearTokens (tr) bayrak altında de token'larını temizler", () => {
it("legacy clearTokens (tr) bayrak altında de servis token'larını temizler", () => {
process.env.PL24_TR_DISABLED = "true";
const svc = makeService();
const { svc } = makeService();
const p = svc as unknown as Exposed;
p.tokenData2 = { accessToken: "x", sessionCookie: "c", expiresAt: new Date(), services: [] };
p.serviceTokens.de.set("vw_parts", { token: "x", expiresAt: Date.now() + 60_000 });
svc.clearTokens();
expect(p.tokenData2).toBeNull();
expect(p.serviceTokens.de.size).toBe(0);
});
});
describe("PL24AuthService — oturum modeli", () => {
it("bir kez login eder, sonraki çağrılar aynı oturumu kullanır (yeniden login yok)", async () => {
const fetchSpy = vi.fn().mockResolvedValue(loginOk());
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService();
const c1 = await svc.getSessionCookieForAccount("de");
const c2 = await svc.getSessionCookieForAccount("de");
expect(c1).toBe("PL24TOKEN=sess-token-1");
expect(c2).toBe(c1);
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
it("eşzamanlı çağrılar tek login paylaşır (single-flight)", async () => {
const fetchSpy = vi.fn().mockImplementation(async () => {
await new Promise((r) => setTimeout(r, 10));
return loginOk();
});
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService();
await Promise.all([
svc.getSessionCookieForAccount("de"),
svc.getSessionCookieForAccount("de"),
svc.getSessionCookieForAccount("de"),
]);
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
it("başka bir süreç oturumu tutuyorsa Redis'ten devralır, login etmez", async () => {
const redis = makeRedis();
redis.store.set("pl24:auth:session:de", {
sessionToken: "shared-token",
loginAt: Date.now(),
lastOkAt: Date.now(),
});
const fetchSpy = vi.fn();
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService({}, redis);
expect(await svc.getSessionCookieForAccount("de")).toBe("PL24TOKEN=shared-token");
expect(fetchSpy).not.toHaveBeenCalled();
});
it("login sadece çerez mint eder; servis token'ı authorize'dan gelir (Bearer'sız)", async () => {
const fetchSpy = vi.fn().mockImplementation(async (url: string) => {
if (String(url).includes("/login")) return loginOk();
return authorizeOk();
});
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService();
await svc.authorizeServiceForAccount("vw_parts", "de");
const authorizeCall = fetchSpy.mock.calls.find((c) => String(c[0]).includes("/authorize"));
expect(authorizeCall).toBeTruthy();
const headers = (authorizeCall?.[1] as { headers: Record<string, string> }).headers;
expect(headers.Cookie).toBe("PL24TOKEN=sess-token-1");
expect(headers.Authorization).toBeUndefined();
expect(headers["User-Agent"]).toMatch(/Chrome\/\d/);
});
it("servis token'ı süresi dolmadan yeniden authorize edilmez", async () => {
const fetchSpy = vi.fn().mockImplementation(async (url: string) => {
if (String(url).includes("/login")) return loginOk();
return authorizeOk();
});
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService();
await svc.authorizeServiceForAccount("vw_parts", "de");
await svc.authorizeServiceForAccount("vw_parts", "de");
const authorizeCalls = fetchSpy.mock.calls.filter((c) => String(c[0]).includes("/authorize"));
expect(authorizeCalls).toHaveLength(1);
});
it("session_status=gone → oturumu düşürür, bir kez yeniden login edip devam eder", async () => {
let authorizeCalls = 0;
const fetchSpy = vi.fn().mockImplementation(async (url: string) => {
if (String(url).includes("/login")) return loginOk(`sess-${authorizeCalls}`);
authorizeCalls += 1;
return authorizeCalls === 1 ? authorizeOk("vw_parts", "gone") : authorizeOk();
});
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService();
const token = await svc.authorizeServiceForAccount("vw_parts", "de");
expect(token).toBeTruthy();
expect(authorizeCalls).toBe(2);
expect(fetchSpy.mock.calls.filter((c) => String(c[0]).includes("/login"))).toHaveLength(2);
});
it("authorize 401 → oturumu düşürür ve tek sefer yeniden dener", async () => {
let authorizeCalls = 0;
const fetchSpy = vi.fn().mockImplementation(async (url: string) => {
if (String(url).includes("/login")) return loginOk();
authorizeCalls += 1;
if (authorizeCalls === 1) {
return {
ok: false,
status: 401,
statusText: "Unauthorized",
headers: { get: () => null, getSetCookie: () => [] },
json: async () => ({}),
};
}
return authorizeOk();
});
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService();
await expect(svc.authorizeServiceForAccount("vw_parts", "de")).resolves.toBeTruthy();
expect(authorizeCalls).toBe(2);
});
it("oturum sınırııldı (412) → tek sefer squeezeOut ile tekrar dener", async () => {
const bodies: string[] = [];
let loginCalls = 0;
const fetchSpy = vi.fn().mockImplementation(async (url: string, opts: { body: string }) => {
if (!String(url).includes("/login")) return authorizeOk();
bodies.push(opts.body);
loginCalls += 1;
return loginCalls === 1
? problem(412, "urn:login:session-limit-exceeded")
: loginOk("after-squeeze");
});
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService();
expect(await svc.getSessionCookieForAccount("de")).toBe("PL24TOKEN=after-squeeze");
expect(JSON.parse(bodies[0]).squeezeOut).toBe(false);
expect(JSON.parse(bodies[1]).squeezeOut).toBe(true);
});
it("P4 header'ı yalnız çerez taşır (authorize isteği atmaz)", async () => {
const fetchSpy = vi.fn().mockResolvedValue(loginOk());
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService();
const headers = await svc.buildFordLegacyHeadersForAccount("opel_parts", "de");
expect(headers.Cookie).toBe("PL24TOKEN=sess-token-1");
expect(headers.Authorization).toBeUndefined();
expect(fetchSpy.mock.calls.filter((c) => String(c[0]).includes("/authorize"))).toHaveLength(0);
});
it("Ford hintstoken değeri oturum token'ıdır", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(loginOk("hint-1")));
const { svc } = makeService();
await svc.getSessionCookieForAccount("de");
expect(svc.getPL24TokenValueForAccount("de")).toBe("hint-1");
});
});
@@ -82,46 +311,58 @@ describe("PL24AuthService — login devre kesici", () => {
it("3 ardışık başarısız login'den sonra açılır ve yeni ağ denemesini keser", async () => {
const fetchSpy = vi.fn().mockRejectedValue(new Error("network down"));
vi.stubGlobal("fetch", fetchSpy);
const p = makeService() as unknown as Exposed;
const { svc } = makeService();
const p = svc as unknown as Exposed;
for (let i = 0; i < 3; i++) {
await expect(p.login2()).rejects.toThrow(/giris hatasi/);
await expect(p.login("de")).rejects.toThrow(/giris hatasi/);
}
// Ağ hatasında squeezeOut denemesi yapılmaz → login başına tek fetch.
expect(fetchSpy).toHaveBeenCalledTimes(3);
// 4. deneme: kesici açık — fetch'e hiç gidilmez.
await expect(p.login2()).rejects.toThrow(/breaker open/);
await expect(p.login("de")).rejects.toThrow(/breaker open/);
expect(fetchSpy).toHaveBeenCalledTimes(3);
});
it("hesap kapalı (account-not-active) → ilk hatada uzun süreli kesici", async () => {
const fetchSpy = vi.fn().mockResolvedValue(problem(400, "urn:login:account-not-active"));
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService();
const p = svc as unknown as Exposed;
await expect(p.login("de")).rejects.toThrow(/giris hatasi/);
await expect(p.login("de")).rejects.toThrow(/breaker open/);
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
it("başarılı login kesici sayacını sıfırlar", async () => {
let failFirst = 2;
const okResponse = {
ok: true,
headers: { get: () => null },
json: async () => ({
token: {
// exp uzak gelecekte olan imzasız-görünümlü JWT payload'ı
access_token: `h.${Buffer.from(
JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600, services: ["x"] }),
).toString("base64url")}.s`,
},
}),
};
const fetchSpy = vi.fn().mockImplementation(async () => {
if (failFirst > 0) {
failFirst -= 1;
throw new Error("network down");
}
return okResponse;
return loginOk();
});
vi.stubGlobal("fetch", fetchSpy);
const p = makeService() as unknown as Exposed;
const { svc } = makeService();
const p = svc as unknown as Exposed;
await expect(p.login2()).rejects.toThrow();
await expect(p.login2()).rejects.toThrow();
await expect(p.login2(true)).resolves.toBeTruthy(); // 3. deneme başarılı → sayaç sıfır
await expect(p.login2(true)).resolves.toBeTruthy(); // kesici açılmadı, akış normal
await expect(p.login("de")).rejects.toThrow();
await expect(p.login("de")).rejects.toThrow();
await expect(p.login("de")).resolves.toBeTruthy();
await expect(p.login("de")).resolves.toBeTruthy();
expect(fetchSpy).toHaveBeenCalledTimes(4);
});
it("saatlik login tavanıılırsa yeni login denenmez", async () => {
const fetchSpy = vi.fn().mockResolvedValue(loginOk());
vi.stubGlobal("fetch", fetchSpy);
const { svc } = makeService();
const p = svc as unknown as Exposed;
for (let i = 0; i < 6; i++) await p.login("de");
await expect(p.login("de")).rejects.toThrow(/login rate limit/);
expect(fetchSpy).toHaveBeenCalledTimes(6);
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -116,7 +116,7 @@ export class PL24FordLegacyService {
}
// Ford / Hyundai-Kia / Nissan / Opel / Volvo devam eder...
await this.authService.authorizeServiceForAccount(serviceName, account);
await this.authService.ensureSession(account);
const html = await this.fetchVinGroupPage(vin, serviceName, account);
if (!html) return null;
@@ -124,8 +124,8 @@ export class PL24FordLegacyService {
const support = this.extractScriptVariable<FordPL24Support>(html, "PL24_SUPPORT");
if (support?.demo || support?.role === "NOT_LOGGED_IN_DEMO") {
this.logger.warn(`P4 legacy: demo mode for ${serviceName}, retrying with fresh auth`);
this.authService.clearTokensForAccount(account);
await this.authService.authorizeServiceForAccount(serviceName, account);
await this.authService.dropSessionForAccount(account, "P4 page 401");
await this.authService.ensureSession(account);
const retryHtml = await this.fetchVinGroupPage(vin, serviceName, account);
if (!retryHtml) return null;
@@ -1110,7 +1110,7 @@ export class PL24FordLegacyService {
this.logger.log(`Ford: fetching vehicle list for ${serviceName}`);
try {
await this.authService.authorizeService(serviceName);
await this.authService.ensureSession("tr");
const config = getServiceConfig(serviceName);
const basePath = config ? `${config.basePath}/${serviceName}` : `/ford/${serviceName}`;
@@ -1126,8 +1126,8 @@ export class PL24FordLegacyService {
let support = this.extractScriptVariable<FordPL24Support>(html, "PL24_SUPPORT");
if (support?.demo || support?.role === "NOT_LOGGED_IN_DEMO") {
this.logger.warn(`Ford: demo mode for ${serviceName}, retrying with fresh auth`);
this.authService.clearTokens();
await this.authService.authorizeService(serviceName);
await this.authService.dropSessionForAccount("tr", "P4 page 401");
await this.authService.ensureSession("tr");
const retryHtml = await this.fetchP4Page(vinGroupUrl, serviceName, true);
if (!retryHtml) return [];
const retrySupport = this.extractScriptVariable<FordPL24Support>(retryHtml, "PL24_SUPPORT");
@@ -1221,7 +1221,7 @@ export class PL24FordLegacyService {
this.logger.log(`HyundaiKia: fetching vehicle list for ${serviceName}`);
try {
await this.authService.authorizeService(serviceName);
await this.authService.ensureSession("tr");
const config = getServiceConfig(serviceName);
const basePath = config
@@ -1306,7 +1306,7 @@ export class PL24FordLegacyService {
this.logger.log(`Nissan: fetching vehicle list for ${serviceName}`);
try {
await this.authService.authorizeService(serviceName);
await this.authService.ensureSession("tr");
const config = getServiceConfig(serviceName);
const basePath = config ? `${config.basePath}/${serviceName}` : `/nissan/${serviceName}`;
@@ -1377,7 +1377,7 @@ export class PL24FordLegacyService {
this.logger.log(`Opel: fetching vehicle list for ${serviceName}`);
try {
await this.authService.authorizeService(serviceName);
await this.authService.ensureSession("tr");
const config = getServiceConfig(serviceName);
const basePath = config ? `${config.basePath}/${serviceName}` : `/opel/${serviceName}`;
@@ -1452,7 +1452,7 @@ export class PL24FordLegacyService {
this.logger.log(`Volvo: fetching vehicle list for ${serviceName}`);
try {
await this.authService.authorizeService(serviceName);
await this.authService.ensureSession("tr");
const config = getServiceConfig(serviceName);
const basePath = config ? `${config.basePath}/${serviceName}` : `/volvo/${serviceName}`;
@@ -1556,7 +1556,7 @@ export class PL24FordLegacyService {
this.logger.log(`Volvo: fetching model config for ${serviceName} mdl=${mdlId}`);
await this.authService.authorizeService(serviceName);
await this.authService.ensureSession("tr");
try {
const config = getServiceConfig(serviceName);
@@ -1626,7 +1626,7 @@ export class PL24FordLegacyService {
this.logger.log(`Ford: fetching model config for ${serviceName} family=${familyId}`);
await this.authService.authorizeService(serviceName);
await this.authService.ensureSession("tr");
const config = getServiceConfig(serviceName);
const arch = config?.architecture;
@@ -1785,7 +1785,7 @@ export class PL24FordLegacyService {
: `Ford: fetching main groups for ${serviceName} family=${familyId} year=${modelYear} engine=${engine} gearbox=${gearbox}`,
);
await this.authService.authorizeService(serviceName);
await this.authService.ensureSession("tr");
try {
const basePath = config ? `${config.basePath}/${serviceName}` : `/ford/${serviceName}`;
@@ -1957,7 +1957,7 @@ export class PL24FordLegacyService {
cacheKey: string,
account: "tr" | "de",
): Promise<PL24DecodedVehicle | null> {
await this.authService.authorizeServiceForAccount(serviceName, account);
await this.authService.ensureSession(account);
const html = await this.fetchVinGroupPage(vin, serviceName, account);
if (!html) return null;
@@ -1965,8 +1965,8 @@ export class PL24FordLegacyService {
const support = this.extractScriptVariable<FordPL24Support>(html, "PL24_SUPPORT");
if (support?.demo || support?.role === "NOT_LOGGED_IN_DEMO") {
this.logger.warn(`Fiat: demo mode for ${serviceName}, retrying with fresh auth`);
this.authService.clearTokensForAccount(account);
await this.authService.authorizeServiceForAccount(serviceName, account);
await this.authService.dropSessionForAccount(account, "P4 demo page (session not accepted)");
await this.authService.ensureSession(account);
const retryHtml = await this.fetchVinGroupPage(vin, serviceName, account);
if (!retryHtml) return null;
@@ -2893,7 +2893,7 @@ export class PL24FordLegacyService {
private async initPsaSession(
serviceName: string,
): Promise<{ jsessionId: string; mode: string; upds: string } | null> {
await this.authService.authorizeService(serviceName);
await this.authService.ensureSession("tr");
const headers = await this.authService.buildFordLegacyHeaders(serviceName);
try {
@@ -3328,7 +3328,7 @@ export class PL24FordLegacyService {
const isDeOnly = LEGACY_DE_SERVICES.has(serviceName);
const account = isDeOnly ? "de" : accountParam;
if (isDeOnly) {
await this.authService.authorizeServiceForAccount(serviceName, "de");
await this.authService.ensureSession("de");
}
// Some catalogs (Volvo vin-group.action) store hrefs relative to the catalog
// directory (e.g. "vin-group.action?group1=…"). Prefix the service basePath
@@ -3358,8 +3358,8 @@ export class PL24FordLegacyService {
if (response.status === 401) {
this.logger.warn(`Ford legacy: 401, refreshing auth (account=${account})`);
this.authService.clearTokensForAccount(account);
await this.authService.authorizeServiceForAccount(serviceName, account);
await this.authService.dropSessionForAccount(account, "P4 page 401");
await this.authService.ensureSession(account);
const newHeaders = await this.authService.buildFordLegacyHeadersForAccount(
serviceName,
account,
@@ -3392,8 +3392,11 @@ export class PL24FordLegacyService {
const support = this.extractScriptVariable<FordPL24Support>(html, "PL24_SUPPORT");
if (support?.demo || support?.role === "NOT_LOGGED_IN_DEMO") {
this.logger.warn(`Ford legacy: demo page for ${serviceName}, re-authing + retry`);
this.authService.clearTokensForAccount(account);
await this.authService.authorizeServiceForAccount(serviceName, account);
await this.authService.dropSessionForAccount(
account,
"P4 demo page (session not accepted)",
);
await this.authService.ensureSession(account);
return this.fetchP4Page(url, serviceName, isFullUrl, account, true);
}
}
@@ -3438,8 +3441,8 @@ export class PL24FordLegacyService {
if (response.status === 401) {
this.logger.warn(`Ford legacy: 401, refreshing auth (account=${account})`);
this.authService.clearTokensForAccount(account);
await this.authService.authorizeServiceForAccount(serviceName, account);
await this.authService.dropSessionForAccount(account, "P4 page 401");
await this.authService.ensureSession(account);
const newHeaders = await this.authService.buildFordLegacyHeadersForAccount(
serviceName,
account,

View File

@@ -455,7 +455,8 @@ export class PL24PsaService {
* entry.action → startup=true (302) → 302 with mode+upds. Returns JSESSIONID/mode/upds.
*/
private async initPsaSession(serviceName: string): Promise<PsaSession | null> {
await this.authService.authorizeService(serviceName);
// P4 PSA pages authenticate off the session cookie alone — no service token.
await this.authService.ensureSession("tr");
const headers = await this.authService.buildFordLegacyHeaders(serviceName);
const dispatcher = await this.psaDispatcher();
const withDispatcher = (o: RequestInit): RequestInit & { dispatcher?: any } =>

View File

@@ -1,13 +1,29 @@
export const PL24_DEFAULTS = {
AUTH_TOKEN_TTL: 3600, // 1 hour in seconds
/** Service JWTs live 600s (measured); refresh this many ms before expiry. */
SERVICE_TOKEN_SKEW_MS: 60_000,
/** PL24TOKEN is a session cookie with no expiry — we keep our copy for a day. */
SESSION_TTL_S: 86_400,
CACHE_PREFIX: "pl24:",
REQUEST_TIMEOUT: 30000,
MAX_RETRIES: 3,
} as const;
/**
* Real Chrome UA. The old value ("…AppleWebKit/537.36" with no Chrome/Safari
* token) matches no real browser and is a cheap automation tell.
*/
export const PL24_USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36";
export const PL24_ENDPOINTS = {
// Auth
LOGIN: "/pl24-appgtw/ext/api/1.0/login",
// Auth — LOGIN is the portal/landing endpoint (returns {loginStatus, sessionToken}
// + Set-Cookie PL24TOKEN). LOGIN_LEGACY is the in-SPA one our old code used; it
// still works and returns a 600s base JWT we no longer need. PL24_LOGIN_API=legacy
// switches back for one release.
LOGIN: "/auth/ext/api/1.1/login",
LOGIN_LEGACY: "/pl24-appgtw/ext/api/1.0/login",
LOGOUT_LEGACY: "/pl24-appgtw/ext/api/1.0/logout",
SESSION: "/auth/ext/api/1.1/session",
AUTHORIZE: "/auth/ext/api/1.1/authorize",
// Catalog

View File

@@ -53,6 +53,58 @@ export interface PL24JWTPayload {
alo: string;
}
/** Portal login (`/auth/ext/api/1.1/login`) request + response. */
export interface PL24LoginRequestV2 {
account: string;
user: string;
password: string;
squeezeOut: boolean;
/** Two-factor confirmation code, when PL24 asks for one. */
code?: string;
}
export interface PL24LoginResponseV2 {
loginStatus?: "OK" | string;
sessionToken?: string;
}
/**
* RFC7807 body PL24 returns on a refused login (HTTP 400/412). `type` carries
* the reason; the UI bundle enumerates these.
*/
export interface PL24LoginProblem {
type?: string;
title?: string;
detail?: string;
/** For two-fa-required: "AUTHENTICATOR" | "EMAIL". */
method?: string;
code?: string;
token?: string;
completionToken?: string;
}
export const PL24_LOGIN_PROBLEM = {
SESSION_LIMIT_EXCEEDED: "urn:login:session-limit-exceeded",
TWO_FA_REQUIRED: "urn:login:two-factor-authentication-required",
TWO_FA_INVALID: "urn:login:two-factor-authentication-invalid-code",
ACCOUNT_PENDING: "urn:login:account-pending",
PRECONDITION_FAILED: "urn:login:precondition-failed",
ACCOUNT_NOT_ACTIVE: "urn:login:account-not-active",
USER_NOT_ACTIVE: "urn:login:user-not-active",
AUTHENTICATION_FAILED: "urn:login:authentication",
} as const;
/**
* One PL24 session = the PL24TOKEN cookie. It has no expiry of its own; it dies
* when PL24 squeezes it out (another login on the same account) or is revoked,
* which surfaces as authorize → 401 or `session_status: "gone"`.
*/
export interface PL24Session {
sessionToken: string;
loginAt: number;
lastOkAt: number;
}
export interface PL24TokenData {
accessToken: string;
refreshToken: string;