MC/website/node/seal-entitlement-store.mjs
2026-11-27 23:43:05 +00:00

41 lines
5.1 KiB
JavaScript

// Alpha 1.0.0.5 recognition storage. Additive: legacy ownership is not deleted.
export const sealEntitlementSchema=Object.freeze([
`CREATE TABLE IF NOT EXISTS seal_entitlements (id CHAR(36) PRIMARY KEY, account_id CHAR(36) NOT NULL, seal_key VARCHAR(100) NOT NULL, source_kind VARCHAR(24) NOT NULL, source_id VARCHAR(160) NOT NULL, granted_by CHAR(36) NULL, granted_at BIGINT NOT NULL, revoked_at BIGINT NULL, revoked_by CHAR(36) NULL, revoke_reason VARCHAR(500) NULL, UNIQUE KEY seal_source_unique(source_kind,source_id,seal_key), INDEX seal_account_active(account_id,revoked_at), INDEX seal_account_key(account_id,seal_key)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`,
`CREATE TABLE IF NOT EXISTS seal_entitlement_events (id CHAR(36) PRIMARY KEY, entitlement_id CHAR(36) NOT NULL, account_id CHAR(36) NOT NULL, seal_key VARCHAR(100) NOT NULL, action VARCHAR(24) NOT NULL, actor_id CHAR(36) NULL, source_kind VARCHAR(24) NOT NULL, source_id VARCHAR(160) NOT NULL, details_json TEXT NULL, created_at BIGINT NOT NULL, INDEX seal_event_account(account_id,created_at), INDEX seal_event_entitlement(entitlement_id,created_at)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`
]);
export async function initializeSealEntitlements(db){for(const sql of sealEntitlementSchema)await db.prepare(sql).run();}
// The API can project both legacy badges and new entitlements during controlled migration.
// No migration runs automatically and no purchase is inferred from a supporter rank.
export async function activeSealEntitlements(db,accountId){
if(typeof accountId!=='string'||!accountId.trim())return [];
const {results=[]}=await db.prepare('SELECT id,seal_key,source_kind,source_id,granted_at FROM seal_entitlements WHERE account_id=? AND revoked_at IS NULL ORDER BY granted_at,seal_key').bind(accountId).all();
return results.map(r=>({id:r.id,key:r.seal_key,source:r.source_kind,sourceId:r.source_id,grantedAt:Number(r.granted_at)}));
}
import {randomUUID} from 'node:crypto';
const validId=v=>typeof v==='string'&&v.length>0&&v.length<=160;
const validSeal=v=>typeof v==='string'&&/^[a-z0-9][a-z0-9_-]{1,99}$/.test(v);
// db.batch must execute atomically, as provided by the existing MySQL adapter.
export async function grantSealEntitlement(db,{accountId,seal,sourceKind,sourceId,actorId=null,details=null}){
if(!validId(accountId)||!validSeal(seal)||!['purchase','staff','migration','system'].includes(sourceKind)||!validId(sourceId)||actorId!==null&&!validId(actorId))throw new TypeError('Invalid entitlement grant');
const existing=await db.prepare('SELECT id,account_id FROM seal_entitlements WHERE source_kind=? AND source_id=? AND seal_key=?').bind(sourceKind,sourceId,seal).first();
if(existing){if(existing.account_id!==accountId)throw new Error('Entitlement source belongs to another account');return {id:existing.id,created:false};}
const id=randomUUID(),now=Date.now();
try{await db.batch([
db.prepare('INSERT INTO seal_entitlements(id,account_id,seal_key,source_kind,source_id,granted_by,granted_at) VALUES(?,?,?,?,?,?,?)').bind(id,accountId,seal,sourceKind,sourceId,actorId,now),
db.prepare('INSERT INTO seal_entitlement_events(id,entitlement_id,account_id,seal_key,action,actor_id,source_kind,source_id,details_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)').bind(randomUUID(),id,accountId,seal,'grant',actorId,sourceKind,sourceId,details===null?null:JSON.stringify(details),now)
]);}catch(error){if(error.code==='ER_DUP_ENTRY'||/UNIQUE|duplicate/i.test(String(error.message))){const winner=await db.prepare('SELECT id,account_id FROM seal_entitlements WHERE source_kind=? AND source_id=? AND seal_key=?').bind(sourceKind,sourceId,seal).first();if(winner){if(winner.account_id!==accountId)throw new Error('Entitlement source belongs to another account');return {id:winner.id,created:false};}}throw error;}
return {id,created:true};
}
export async function revokeSealEntitlement(db,{entitlementId,actorId,reason}){
if(!validId(entitlementId)||!validId(actorId)||typeof reason!=='string'||!reason.trim()||reason.length>500)throw new TypeError('Invalid entitlement revocation');
const row=await db.prepare('SELECT id,account_id,seal_key,source_kind,source_id,revoked_at FROM seal_entitlements WHERE id=?').bind(entitlementId).first();
if(!row)return {found:false,revoked:false};
if(row.revoked_at!==null&&row.revoked_at!==undefined)return {found:true,revoked:false};
const now=Date.now();
try{await db.batch([
{async run(connection){const result=await db.prepare('UPDATE seal_entitlements SET revoked_at=?,revoked_by=?,revoke_reason=? WHERE id=? AND revoked_at IS NULL').bind(now,actorId,reason.trim(),entitlementId).run(connection);if(!result.meta?.changes)throw new Error('entitlement-already-revoked');return result;}},
db.prepare('INSERT INTO seal_entitlement_events(id,entitlement_id,account_id,seal_key,action,actor_id,source_kind,source_id,details_json,created_at) VALUES(?,?,?,?,?,?,?,?,?,?)').bind(randomUUID(),entitlementId,row.account_id,row.seal_key,'revoke',actorId,row.source_kind,row.source_id,JSON.stringify({reason:reason.trim()}),now)
]);}catch(error){if(error.message==='entitlement-already-revoked')return {found:true,revoked:false};throw error;}
return {found:true,revoked:true};
}