Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : MacLustr Social Engine & Remote Navigator8 * File : packages/policy-engine/src/index.ts9 * Module : policy-engine10 * Repository : https://git.spboucher.ai/maclustr-social11 * Project Website : https://social.spboucher.ai12 * Created : 2026-12-0113 * Last Modified : 2026-12-0114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Policy engine: pure decisions. No agent can call a mutator here — the active policy is loaded43// read-only from policy_versions and only a human owner can activate a new version.44import { z } from 'zod';45import type { JobMode, Role, SessionState } from '@mls/contracts';46import { AGENT_FORBIDDEN_STATES, ROLE_RANK } from '@mls/contracts';4748export const AutomationLevel = z.enum(['forbidden', 'manual_assisted', 'prepare_only', 'auto_submit']);49export type AutomationLevel = z.infer<typeof AutomationLevel>;50const LEVEL_RANK: Record<AutomationLevel, number> = { forbidden: 0, manual_assisted: 1, prepare_only: 2, auto_submit: 3 };5152export const PolicyDocument = z.object({53 platforms: z.array(z.object({54 hostSuffix: z.string().regex(/^[a-z0-9.:-]{3,120}$/),55 automation: AutomationLevel,56 /** Written basis for the level (terms clause, written permission reference…). */57 basis: z.string().min(10).max(2000),58 }).strict()).max(50),59 navigator: z.object({60 allowedHosts: z.array(z.string().regex(/^[a-z0-9.:-]{3,120}$/)).max(100),61 clipboard: z.boolean(),62 humanInsertApprovedText: z.boolean(),63 downloads: z.literal(false),64 idleLeaseSeconds: z.number().int().min(15).max(600),65 }).strict(),66 approvals: z.object({ required: z.literal(true), agentsMayApprove: z.literal(false) }).strict(),67 frequency: z.object({ hardMaxPerPagePerDay: z.number().int().min(1).max(20), hardMinIntervalMinutes: z.number().int().min(0).max(1440) }).strict(),68 ai: z.object({ monthlyBudgetUsd: z.number().min(0).max(10000), perRunMaxUsd: z.number().min(0).max(100), sendScreenshots: z.enum(['never', 'redacted_only']) }).strict(),69 bulkEngagement: z.literal('forbidden'),70}).strict();71export type PolicyDocument = z.infer<typeof PolicyDocument>;7273export const META_BASIS = "Conditions de service Facebook (en vigueur le 1er janvier 2025), art. 3.2.3 : « You may not access or collect data from our Products using automated means (without our prior permission) » ; Automated Data Collection Terms (7 octobre 2024), art. 2 et 3 : permission écrite expresse requise. Aucune permission obtenue : flux manuel assisté seulement.";7475export function defaultPolicy(fixtureHost?: string): PolicyDocument {76 const meta = ['facebook.com', 'fb.com', 'meta.com', 'messenger.com', 'instagram.com'];77 const doc: PolicyDocument = {78 platforms: meta.map((h) => ({ hostSuffix: h, automation: 'manual_assisted' as const, basis: META_BASIS })),79 navigator: {80 allowedHosts: ['facebook.com', 'fbcdn.net', 'fbsbx.com', 'fb.com', 'meta.com', 'facebook.net', 'accountscenter.facebook.com'],81 clipboard: false, humanInsertApprovedText: true, downloads: false, idleLeaseSeconds: 45,82 },83 approvals: { required: true, agentsMayApprove: false },84 frequency: { hardMaxPerPagePerDay: 4, hardMinIntervalMinutes: 60 },85 ai: { monthlyBudgetUsd: 50, perRunMaxUsd: 1, sendScreenshots: 'redacted_only' },86 bulkEngagement: 'forbidden',87 };88 if (fixtureHost) {89 doc.platforms.push({ hostSuffix: fixtureHost, automation: 'auto_submit', basis: 'Site de fixtures synthétiques servi localement par MacLustr ; aucune plateforme tierce.' });90 doc.navigator.allowedHosts.push(fixtureHost);91 }92 return doc;93}9495export function hostMatches(host: string, suffix: string): boolean {96 host = host.toLowerCase(); suffix = suffix.toLowerCase();97 return host === suffix || host.endsWith('.' + suffix);98}99function hostOf(u: URL): string { return u.port ? `${u.hostname}:${u.port}` : u.hostname; }100101/** RFC1918, loopback, link-local (cloud metadata 169.254.169.254), CGNAT (WireGuard 10.67/100.64), IPv6 local. */102export function isPrivateAddress(hostname: string): boolean {103 const h = hostname.replace(/^\[|\]$/g, '').toLowerCase();104 if (h === 'localhost' || h.endsWith('.localhost') || h.endsWith('.local') || h.endsWith('.internal') || h === 'metadata.google.internal') return true;105 const m = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);106 if (m) {107 const [a, b] = [Number(m[1]), Number(m[2])];108 return a === 10 || a === 127 || a === 0 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127) || a >= 224;109 }110 if (/^\d+$/.test(h) || /^0x[0-9a-f]+$/.test(h)) return true; // decimal / hex encoded IPv4111 if (h.includes(':')) return h === '::1' || h === '::' || h.startsWith('fe80') || h.startsWith('fc') || h.startsWith('fd') || h.startsWith('::ffff:');112 return false;113}114115export type NavDecision = { allow: true } | { allow: false; reason: string };116/** Decides whether the remote browser may load a URL (top-level or sub-resource). */117export function checkNavigation(policy: PolicyDocument, rawUrl: string): NavDecision {118 let u: URL;119 try { u = new URL(rawUrl); } catch { return { allow: false, reason: 'invalid_url' }; }120 if (u.protocol === 'about:' && rawUrl === 'about:blank') return { allow: true };121 if (u.protocol === 'data:' || u.protocol === 'blob:') return { allow: true }; // inline resources only, never navigable from the address bar (gateway refuses)122 if (u.protocol !== 'https:' && u.protocol !== 'http:' && u.protocol !== 'wss:' && u.protocol !== 'ws:') return { allow: false, reason: 'scheme_forbidden' };123 if (u.username || u.password) return { allow: false, reason: 'credentials_in_url' };124 const host = hostOf(u);125 const listed = policy.navigator.allowedHosts.some((s) => hostMatches(host, s) || hostMatches(u.hostname, s));126 if (!listed) return { allow: false, reason: 'host_not_allowed' };127 // A private address is only reachable when it is listed with its exact host:port (fixture server).128 if (isPrivateAddress(u.hostname) && !policy.navigator.allowedHosts.includes(host)) return { allow: false, reason: 'private_network' };129 if ((u.protocol === 'http:' || u.protocol === 'ws:') && !isPrivateAddress(u.hostname)) return { allow: false, reason: 'plaintext_forbidden' };130 return { allow: true };131}132export function isAddressBarUrlAllowed(policy: PolicyDocument, rawUrl: string): NavDecision {133 try { const u = new URL(rawUrl); if (u.protocol !== 'https:' && u.protocol !== 'http:') return { allow: false, reason: 'scheme_forbidden' }; } catch { return { allow: false, reason: 'invalid_url' }; }134 return checkNavigation(policy, rawUrl);135}136137/** Highest automation level the policy grants for a URL. Unknown hosts get 'forbidden'. */138export function automationLevelFor(policy: PolicyDocument, rawUrl: string): { level: AutomationLevel; basis: string } {139 let u: URL;140 try { u = new URL(rawUrl); } catch { return { level: 'forbidden', basis: 'invalid_url' }; }141 const host = hostOf(u);142 const hit = policy.platforms.filter((p) => hostMatches(host, p.hostSuffix) || hostMatches(u.hostname, p.hostSuffix)).sort((a, b) => b.hostSuffix.length - a.hostSuffix.length)[0];143 return hit ? { level: hit.automation, basis: hit.basis } : { level: 'forbidden', basis: 'Hôte absent de la politique.' };144}145/** Clamp a requested job mode to what the platform policy allows. */146export function effectiveJobMode(policy: PolicyDocument, pageUrl: string, requested: JobMode): { mode: JobMode | null; level: AutomationLevel; basis: string } {147 const { level, basis } = automationLevelFor(policy, pageUrl);148 if (level === 'forbidden') return { mode: null, level, basis };149 const want: AutomationLevel = requested;150 const granted = LEVEL_RANK[want] <= LEVEL_RANK[level] ? want : level;151 return { mode: granted as JobMode, level, basis };152}153export function recipeAllowedOn(policy: PolicyDocument, url: string, purpose: string): NavDecision {154 const { level } = automationLevelFor(policy, url);155 const needed: AutomationLevel = purpose === 'submit' ? 'auto_submit' : 'prepare_only';156 return LEVEL_RANK[level] >= LEVEL_RANK[needed] ? { allow: true } : { allow: false, reason: `automation_${level}` };157}158159export function agentMayAct(state: SessionState, emergencyStop: boolean): NavDecision {160 if (emergencyStop) return { allow: false, reason: 'emergency_stop' };161 if (AGENT_FORBIDDEN_STATES.includes(state)) return { allow: false, reason: `state_${state}` };162 return { allow: true };163}164export function captureAllowed(state: SessionState, emergencyStop: boolean): NavDecision {165 return agentMayAct(state, emergencyStop);166}167168export type ActorRef = { kind: 'user' | 'agent' | 'worker' | 'system'; id: string; role?: Role };169export function canApprove(actor: ActorRef, opts: { authorId: string; allowSelfApproval: boolean; brandRole?: Role }): NavDecision {170 if (actor.kind !== 'user') return { allow: false, reason: 'only_humans_approve' };171 const role = opts.brandRole ?? actor.role ?? 'viewer';172 if (ROLE_RANK[role] < ROLE_RANK.approver) return { allow: false, reason: 'role_insufficient' };173 if (actor.id === opts.authorId && !opts.allowSelfApproval) return { allow: false, reason: 'self_approval_forbidden' };174 return { allow: true };175}176export function hasRole(role: Role | undefined, min: Role): boolean { return !!role && ROLE_RANK[role] >= ROLE_RANK[min]; }177178/** Frequency check: brand limits can only be stricter than the policy's hard caps. */179export function checkFrequency(policy: PolicyDocument, brand: { maxPerDay: number; minIntervalMinutes: number }, slot: Date, others: Date[], timezone: string): NavDecision {180 const maxPerDay = Math.min(brand.maxPerDay, policy.frequency.hardMaxPerPagePerDay);181 const minGap = Math.max(brand.minIntervalMinutes, policy.frequency.hardMinIntervalMinutes);182 const day = localDay(slot, timezone);183 const sameDay = others.filter((d) => localDay(d, timezone) === day).length;184 if (sameDay + 1 > maxPerDay) return { allow: false, reason: 'max_per_day' };185 for (const d of others) if (Math.abs(d.getTime() - slot.getTime()) < minGap * 60_000) return { allow: false, reason: 'min_interval' };186 return { allow: true };187}188/** Local calendar day in an IANA zone (DST-safe: uses Intl, not fixed offsets). */189export function localDay(d: Date, timezone: string): string {190 return new Intl.DateTimeFormat('en-CA', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit' }).format(d);191}192193const CHALLENGE = [/\/checkpoint\//i, /two[_-]?step|two[_-]?factor|2fa/i, /captcha/i, /\/recover\//i, /\/security\/|securitycheck/i, /confirmemail|identity\/confirm/i];194const LOGIN = [/\/login(\.php|\/|\?|$)/i, /\/loginpage/i, /[?&]next=/i];195/** URL-based classification of what the remote page is asking for. Never inspects typed data. */196export function classifyUrl(rawUrl: string): 'security_challenge' | 'login_required' | 'ok' {197 let path = rawUrl;198 try { const u = new URL(rawUrl); path = u.pathname + u.search; } catch { /* keep raw */ }199 if (CHALLENGE.some((r) => r.test(path))) return 'security_challenge';200 if (LOGIN.some((r) => r.test(path))) return 'login_required';201 return 'ok';202}203