import { GuestAccountStore, GuestError, GuestSession, TextStorage } from './GuestContracts'; /** 按产品和服务隔离身份,成功会话单独提交。 / Isolate identities by product/service and commit successful sessions separately. */ export class GuestSessionStore implements GuestAccountStore { readonly identityKey: string; readonly sessionKey: string; constructor(private readonly storage: TextStorage, origin: string, product: string) { const scope = encodeURIComponent(`${origin.replace(/\/+$/, '')}|${product}`); this.identityKey = `fruit-pop.auth.identity.v1.${scope}`; this.sessionKey = `fruit-pop.auth.session.v1.${scope}`; } identity(create: () => string): string { try { const existing = this.storage.getItem(this.identityKey); const identity = existing ?? create(); if (typeof identity !== 'string' || !/^[a-zA-Z0-9-]{16,128}$/.test(identity)) { throw new GuestError('identity', 'Unable to restore a secure guest identity.'); } if (existing === null) this.writeVerified(this.identityKey, identity); return identity; } catch (error) { throw this.storageError(error); } } save(session: GuestSession): void { try { this.writeVerified(this.sessionKey, JSON.stringify(session)); } catch (error) { throw this.storageError(error); } } private writeVerified(key: string, text: string): void { this.storage.setItem(key, text); if (this.storage.getItem(key) !== text) throw new GuestError('storage', 'Unable to save guest data. Please retry.'); } private storageError(error: unknown): GuestError { return error instanceof GuestError ? error : new GuestError('storage', 'Guest storage is unavailable. Please retry.'); } }