<?xml version="1.0" encoding="UTF-8"?><unload unload_date="2026-10-29 13:30:30">
<sys_remote_update_set action="INSERT_OR_UPDATE">
<application display_value="Global">global</application>
<application_name>Global</application_name>
<application_scope>global</application_scope>
<application_version/>
<collisions/>
<commit_date/>
<deleted/>
<description/>
<inserted/>
<name>ReversingLabs SIR Integration Global Prerequisites 1.0.6</name>
<origin_sys_id/>
<parent display_value=""/>
<release_date/>
<remote_base_update_set display_value=""/>
<remote_parent_id/>
<remote_sys_id>9e3cfa383bffc31019b06dc5e4e45a25</remote_sys_id>
<state>loaded</state>
<summary/>
<sys_class_name>sys_remote_update_set</sys_class_name>
<sys_created_by>admin</sys_created_by>
<sys_created_on>2026-10-29 13:30:29</sys_created_on>
<sys_id>5bce30ac3b905f1019b06dc5e4e45a3f</sys_id>
<sys_mod_count>0</sys_mod_count>
<sys_updated_by>admin</sys_updated_by>
<sys_updated_on>2026-10-29 13:30:29</sys_updated_on>
<update_set display_value=""/>
<update_source display_value=""/>
<updated/>
</sys_remote_update_set>
<sys_update_xml action="INSERT_OR_UPDATE">
<action>INSERT_OR_UPDATE</action>
<application display_value="Global">global</application>
<category>customer</category>
<comments/>
<name>sys_script_include_bdec42e73ba28b1019b06dc5e4e45a0a</name>
<payload>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;record_update table="sys_script_include"&gt;&lt;sys_script_include action="INSERT_OR_UPDATE"&gt;&lt;access&gt;public&lt;/access&gt;&lt;active&gt;true&lt;/active&gt;&lt;api_name&gt;global.RLOAuthTokenGenerator&lt;/api_name&gt;&lt;caller_access/&gt;&lt;client_callable&gt;false&lt;/client_callable&gt;&lt;description&gt;OAuth token generator (global prereq)&lt;/description&gt;&lt;mobile_callable&gt;false&lt;/mobile_callable&gt;&lt;name&gt;RLOAuthTokenGenerator&lt;/name&gt;&lt;sandbox_callable&gt;false&lt;/sandbox_callable&gt;&lt;script&gt;&lt;![CDATA[// =========================================================================
// global.RLOAuthTokenGenerator - OAuth Bearer Token Generator
// =========================================================================
// Scope: Global
// Purpose: Generate and cache OAuth 2.0 Bearer tokens for API integration
// Entry points:
//   - getOAuthToken() — always generate new token (manual/testing)
//   - getCurrentOAuthToken() — return cached if valid, else generate new (internal use)
// Called by: RLIntegration dispatcher via sysparm_name = 'generateoauthtoken'
// Access: Protected by RLIntegration._checkAccess() - requires admin role
// =========================================================================

var RLOAuthTokenGenerator = Class.create();
global.RLOAuthTokenGenerator.prototype = {

    getOAuthToken: function() {
        try {
            gs.debug('[global.RLOAuthTokenGenerator.getOAuthToken] Querying global oauth_entity...');

            var grOAuth = new GlideRecord('oauth_entity');
            grOAuth.addQuery('name', 'ReversingLabs Inbound API Client (Global)');
            grOAuth.setLimit(1);
            grOAuth.query();

            if (!grOAuth.next()) {
                gs.warn('[global.RLOAuthTokenGenerator.getOAuthToken] OAuth entity "ReversingLabs Inbound API Client (Global)" not found');
                return { success: false, message: 'OAuth entity not found' };
            }

            var clientId = grOAuth.getValue('client_id');
            var clientSecret = '';
            // Read client_secret from property or OAuth entity
            clientSecret = gs.getProperty('x_rligh_revers_0.rl_oauth_client_secret', '');
            if (!clientSecret) {
                clientSecret = grOAuth.getValue('client_secret');
            }

            if (!clientId || !clientSecret) {
                gs.warn('[global.RLOAuthTokenGenerator.getOAuthToken] Client ID or Secret is empty');
                return { success: false, message: 'Client ID or Secret missing' };
            }

            gs.debug('[global.RLOAuthTokenGenerator.getOAuthToken] Requesting token from /oauth_token.do...');

            var req = new sn_ws.RESTMessageV2();
            var instanceUrl = gs.getProperty('glide.servlet.uri').replace(/\/$/, '');
            req.setEndpoint(instanceUrl + '/oauth_token.do');
            req.setHttpMethod('POST');
            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            req.setRequestHeader('Accept', 'application/json');

            var body = 'grant_type=client_credentials' +
                '&amp;client_id=' + encodeURIComponent(clientId) +
                '&amp;client_secret=' + encodeURIComponent(clientSecret);
            req.setRequestBody(body);
            req.setHttpTimeout(10000);

            var response = req.execute();
            var statusCode = response.getStatusCode();
            var responseBody = response.getBody();

            if (statusCode === 200) {
                var tokenData = JSON.parse(responseBody);
                if (tokenData.access_token) {
                    gs.debug('[global.RLOAuthTokenGenerator.getOAuthToken] Token generated successfully');
                    var expirySeconds = tokenData.expires_in || 31536000;
                    var expiryMs = new Date().getTime() + expirySeconds * 1000;
                    this.storeToken(tokenData.access_token, expiryMs);
                    return {
                        success: true,
                        access_token: tokenData.access_token,
                        expires_in: expirySeconds,
                        token_type: tokenData.token_type || 'Bearer'
                    };
                }
            }

            gs.warn('[global.RLOAuthTokenGenerator.getOAuthToken] OAuth endpoint returned status ' + statusCode);
            return {
                success: false,
                message: 'Token request failed: HTTP ' + statusCode
            };
        } catch (err) {
            gs.error('[global.RLOAuthTokenGenerator.getOAuthToken] Exception: ' + err.message);
            return { success: false, message: 'Exception: ' + err.message };
        }
    },

    getCurrentOAuthToken: function() {
        try {
            var expiryMs = parseInt(gs.getProperty('x_rligh_revers_0.rl_oauth_token_expiry', '0'), 10);
            var nowMs = new Date().getTime();

            if (expiryMs &gt; nowMs + 60000) {
                var cached = this.readToken();
                if (cached.token) {
                    gs.debug('[global.RLOAuthTokenGenerator.getCurrentOAuthToken] Returning cached token');
                    return { success: true, access_token: cached.token };
                }
            }

            gs.debug('[global.RLOAuthTokenGenerator.getCurrentOAuthToken] Token expired or missing, generating new');
            return this.getOAuthToken();
        } catch (err) {
            gs.error('[global.RLOAuthTokenGenerator.getCurrentOAuthToken] ' + err.message);
            return { success: false, message: err.message };
        }
    },

    storeToken: function(token, expiryMs) {
        try {
            var credentialName = 'ReversingLabs OAuth Bearer Token';
            var credGR = new GlideRecord('discovery_credentials');
            credGR.addQuery('name', credentialName);
            credGR.setLimit(1);
            credGR.query();

            if (credGR.next()) {
                credGR.setValue('password', token);
                credGR.update();
                gs.info('[global.RLOAuthTokenGenerator.storeToken] Updated existing OAuth credential');
            } else {
                credGR = new GlideRecord('discovery_credentials');
                credGR.setValue('name', credentialName);
                credGR.setValue('password', token);
                credGR.insert();
                gs.info('[global.RLOAuthTokenGenerator.storeToken] Created new OAuth credential');
            }

            gs.setProperty('x_rligh_revers_0.rl_oauth_token_expiry', expiryMs.toString());
        } catch (err) {
            gs.error('[global.RLOAuthTokenGenerator.storeToken] Failed to store token: ' + err.message);
            throw err;
        }
    },

    readToken: function() {
        try {
            var credentialName = 'ReversingLabs OAuth Bearer Token';
            var credGR = new GlideRecord('discovery_credentials');
            credGR.addQuery('name', credentialName);
            credGR.setLimit(1);
            credGR.query();

            if (credGR.next()) {
                var token = credGR.getValue('password');
                if (token) {
                    return { token: token };
                }
            }

            return { token: null };
        } catch (err) {
            gs.error('[global.RLOAuthTokenGenerator.readToken] Failed to read token: ' + err.message);
            return { token: null };
        }
    },

    type: 'global.RLOAuthTokenGenerator'
};]]&gt;&lt;/script&gt;&lt;sys_class_name&gt;sys_script_include&lt;/sys_class_name&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:04:17&lt;/sys_created_on&gt;&lt;sys_id&gt;bdec42e73ba28b1019b06dc5e4e45a0a&lt;/sys_id&gt;&lt;sys_mod_count&gt;6&lt;/sys_mod_count&gt;&lt;sys_name&gt;RLOAuthTokenGenerator&lt;/sys_name&gt;&lt;sys_package display_value="Global" source="global"&gt;global&lt;/sys_package&gt;&lt;sys_policy/&gt;&lt;sys_scope display_value="Global"&gt;global&lt;/sys_scope&gt;&lt;sys_update_name&gt;sys_script_include_bdec42e73ba28b1019b06dc5e4e45a0a&lt;/sys_update_name&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-10-07 01:27:49&lt;/sys_updated_on&gt;&lt;/sys_script_include&gt;&lt;sys_es_latest_script action="INSERT_OR_UPDATE"&gt;&lt;id&gt;bdec42e73ba28b1019b06dc5e4e45a0a&lt;/id&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:04:17&lt;/sys_created_on&gt;&lt;sys_id&gt;a30d46e73ba28b1019b06dc5e4e45a81&lt;/sys_id&gt;&lt;sys_mod_count&gt;0&lt;/sys_mod_count&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-08-13 03:04:17&lt;/sys_updated_on&gt;&lt;table&gt;sys_script_include&lt;/table&gt;&lt;use_es_latest&gt;true&lt;/use_es_latest&gt;&lt;/sys_es_latest_script&gt;&lt;/record_update&gt;</payload>
<payload_hash>-400055823</payload_hash>
<remote_update_set display_value="ReversingLabs SIR Integration Global Prerequisites 1.0.6">5bce30ac3b905f1019b06dc5e4e45a3f</remote_update_set>
<replace_on_upgrade>false</replace_on_upgrade>
<sys_created_by>admin</sys_created_by>
<sys_created_on>2026-10-29 13:30:29</sys_created_on>
<sys_id>13ce30ac3b905f1019b06dc5e4e45a42</sys_id>
<sys_mod_count>0</sys_mod_count>
<sys_recorded_at>1a113f954c70000001</sys_recorded_at>
<sys_updated_by>admin</sys_updated_by>
<sys_updated_on>2026-10-29 13:30:29</sys_updated_on>
<table/>
<target_name>RLOAuthTokenGenerator</target_name>
<type>Script Include</type>
<update_domain>global</update_domain>
<update_guid>ba668d59ba3f4310011fd396b10b4c69</update_guid>
<update_guid_history>ba668d59ba3f4310011fd396b10b4c69:-400055823,096c7278c8ffc31019f928bf39406ca5:1715473485,fb0d5ab8f4fbc310323c1297c8878590:-1937917929,8238362a312b071089cc76feb9cdf036:1715473485,a4a3827e0b178710724e789017d9b95e:-1937917929,5291b149cfdf4f10aa48b8ee9330923a:1715473485,e30d46e7b9a28b1079cee0681e828485:-1937917929</update_guid_history>
<update_set display_value=""/>
<view/>
</sys_update_xml>
<sys_update_xml action="INSERT_OR_UPDATE">
<action>INSERT_OR_UPDATE</action>
<application display_value="Global">global</application>
<category>customer</category>
<comments/>
<name>sys_script_include_556e8e6b3ba28b1019b06dc5e4e45ae5</name>
<payload>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;record_update table="sys_script_include"&gt;&lt;sys_script_include action="INSERT_OR_UPDATE"&gt;&lt;access&gt;public&lt;/access&gt;&lt;active&gt;true&lt;/active&gt;&lt;api_name&gt;global.RLPostInstallInitialization&lt;/api_name&gt;&lt;caller_access/&gt;&lt;client_callable&gt;false&lt;/client_callable&gt;&lt;description&gt;Post-install initialization (global prereq)&lt;/description&gt;&lt;mobile_callable&gt;false&lt;/mobile_callable&gt;&lt;name&gt;RLPostInstallInitialization&lt;/name&gt;&lt;sandbox_callable&gt;false&lt;/sandbox_callable&gt;&lt;script&gt;&lt;![CDATA[// =========================================================================

// 2026-10-05: platform property writes removed (certification); does not write global properties.

// global.RLPostInstallInitialization - Post-Install Setup Script

// =========================================================================

// Scope: Global

// Purpose: Auto-initialize app infrastructure after installation

// Called by: Guided setup wizard completion OR manual trigger

// Idempotent: Yes - safe to run multiple times

// =========================================================================



var RLPostInstallInitialization = Class.create();

global.RLPostInstallInitialization.prototype = {

    initialize: function () {

        this.logPrefix = '[RL-INIT]';

        this.scope = 'x_rligh_revers_0';
        // 2026-10-06: resolve the scope SYS_ID. Assigning the NAME to sys_scope/sys_package produced
        // records that export with scope=global and are refused on commit (scope mismatch).
        var _scopeGr = new GlideRecord('sys_scope');
        _scopeGr.addQuery('name', this.scope);
        _scopeGr.setLimit(1);
        _scopeGr.query();
        this.scopeId = _scopeGr.next() ? _scopeGr.getUniqueValue() : 'global';

        this.logs = [];

    },



    run: function (password) {

        gs.info(this.logPrefix + ' Starting post-install initialization', this.logPrefix);



        try {

            // GUARD (2026-10-06): the scoped application must be installed first.

            try { var _appOk = !!new x_rligh_revers_0.RLIntegration(); } catch (e0) {

                return { success: false, message: "ReversingLabs application update set is not installed - install the scoped application before post-install initialization." };

            }

            this.createTablesIfMissing();

            // 2026-10-13 DEPRECATED: notification_queue/_suppression tables are unused.
            // Notifications are tracked on the broadcast queue via notification_sent_at
            // (see RLNotificationEngine). Creation disabled to stop stray global u_ tables.
            // this.createNotificationTablesIfMissing();

            this.createRolesIfMissing();

            this.createAclsIfMissing();

            this.setSystemPropertiesDefaults();

            this.setPhase22PropertiesDefaults();



            // 2026-10-01: worker user/roles MUST exist BEFORE the polling job is enabled and

            // repointed, otherwise run_as points at a stale/nonexistent user sys_id from the

            // shipped record and the loopback SRR calls fail (correctness fix for fresh installs).

            if (password) {

                var workerResult = this.configureServiceAccount(password);

                if (!workerResult.success) {

                    return workerResult;

                }

            }

            this.ensureWorkerUserExists();

            this.configureServiceWorkerRoles();



            this.createOrEnableBackgroundJob();

            this.applyPollingInterval(); // legacy seconds cadence (run_interval/run_period) for polling job

            this.createPhase22JobsIfMissing();



            this.ensureOAuthInfrastructure();

            this.activateCapabilityImplementations();



            this.logSummary();



            gs.info(this.logPrefix + ' ✅ Post-install initialization complete', this.logPrefix);

            return {

                success: true,

                message: 'ReversingLabs SIR Integration initialized successfully',

                logs: this.logs

            };

        } catch (e) {

            gs.error(this.logPrefix + ' ❌ ERROR: ' + e.message, this.logPrefix);

            this.logs.push('ERROR: ' + e.message);

            return {

                success: false,

                message: 'Initialization failed: ' + e.message,

                logs: this.logs

            };

        }

    },



    createTablesIfMissing: function () {

        gs.info(this.logPrefix + ' Creating tables if missing', this.logPrefix);



        var tables = [

            {

                name: this.scope + '_reversinglabs_polling_queue',

                label: 'ReversingLabs Polling Queue',

                description: 'Queue for asynchronous observable enrichment tasks'

            },

            {

                name: this.scope + '_reversinglabs_integration_logs',

                label: 'ReversingLabs Integration Logs',

                description: 'Integration events and error logs'

            }

        ];



        tables.forEach((function (table) {

            var tableGr = new GlideRecord('sys_db_object');

            tableGr.addQuery('name', table.name);

            tableGr.query();



            if (!tableGr.next()) {

                var newTable = new GlideRecord('sys_db_object');

                newTable.name = table.name;

                newTable.label = table.label;

                newTable.super_class = 'task';

                newTable.sys_scope = this.scopeId;

                newTable.insert();

                this.logs.push('✓ Table created: ' + table.name);

                gs.info(this.logPrefix + ' ✓ Table created: ' + table.name, this.logPrefix);

            } else {

                this.logs.push('✓ Table exists: ' + table.name);

            }

        }).bind(this));

    },



    createRolesIfMissing: function () {

        gs.info(this.logPrefix + ' Creating app roles if missing', this.logPrefix);



        var roles = [

            { name: this.scope + '.admin', description: 'ReversingLabs SIR Admin' },

            { name: this.scope + '.user', description: 'ReversingLabs SIR User' }

        ];



        roles.forEach((function (role) {

            var roleGr = new GlideRecord('sys_user_role');

            roleGr.addQuery('name', role.name);

            roleGr.query();



            if (!roleGr.next()) {

                var newRole = new GlideRecord('sys_user_role');

                newRole.name = role.name;

                newRole.description = role.description;

                newRole.sys_scope = this.scopeId;

                newRole.insert();

                this.logs.push('✓ Role created: ' + role.name);

                gs.info(this.logPrefix + ' ✓ Role created: ' + role.name, this.logPrefix);

            } else {

                this.logs.push('✓ Role exists: ' + role.name);

            }

        }).bind(this));

    },



    createAclsIfMissing: function () {

        // 2026-10-05 (cert): table ACL roles are platform admin only; the integration service

        // account reaches these tables via integration_service / run-as-system jobs.

        gs.info(this.logPrefix + ' Creating ACLs if missing', this.logPrefix);



        var acls = [
            {
                type: 'record',
                name: this.scope + '_reversinglabs_polling_queue',
                operation: 'read',
                role: 'sn_si.admin'
            },
            {
                type: 'record',
                name: this.scope + '_reversinglabs_polling_queue',
                operation: 'write',
                role: 'sn_si.admin'
            },
            {
                type: 'record',
                name: this.scope + '_reversinglabs_polling_queue',
                operation: 'create',
                role: 'sn_si.admin'
            },
            {
                type: 'record',
                name: this.scope + '_reversinglabs_polling_queue',
                operation: 'delete',
                role: 'sn_si.admin'
            },
            {
                type: 'record',
                name: this.scope + '_reversinglabs_integration_logs',
                operation: 'read',
                role: 'sn_si.admin'
            },
            {
                type: 'record',
                name: this.scope + '_reversinglabs_integration_logs',
                operation: 'write',
                role: 'sn_si.admin'
            },
            {
                type: 'record',
                name: this.scope + '_reversinglabs_integration_logs',
                operation: 'create',
                role: 'sn_si.admin'
            },
            {
                type: 'record',
                name: this.scope + '_reversinglabs_integration_logs',
                operation: 'delete',
                role: 'sn_si.admin'
            }
        ];



        acls.forEach((function (acl) {

            var aclGr = new GlideRecord('sys_security_acl');

            aclGr.addQuery('type', acl.type);

            aclGr.addQuery('name', acl.name);

            aclGr.addQuery('operation', acl.operation);

            aclGr.addQuery('role', acl.role);

            aclGr.query();



            if (!aclGr.next()) {

                var newAcl = new GlideRecord('sys_security_acl');

                newAcl.type = acl.type;

                newAcl.name = acl.name;

                newAcl.operation = acl.operation;

                newAcl.role = acl.role;

                newAcl.sys_scope = this.scopeId;

                newAcl.active = true;

                newAcl.insert();

                this.logs.push('✓ ACL created: ' + acl.name + ' (' + acl.operation + ')');

                gs.info(this.logPrefix + ' ✓ ACL created: ' + acl.name, this.logPrefix);

            }

        }).bind(this));

    },



    setSystemPropertiesDefaults: function () {

        gs.info(this.logPrefix + ' Setting system property defaults', this.logPrefix);



        var properties = [

            { name: this.scope + '.reversinglabs_api_url', value: 'https://a1000.reversinglabs.com', type: 'string' },

            { name: this.scope + '.rl_auto_upload', value: 'true', type: 'boolean' },

            { name: this.scope + '.rl_upload_max_size_mb', value: '500', type: 'integer' },

            { name: this.scope + '.rl_api_timeout', value: '30', type: 'integer' },

            { name: this.scope + '.rl_queue_rate_limit', value: '5', type: 'integer' },

            { name: this.scope + '.rl_cascade_dns_enabled', value: 'true', type: 'boolean' },

            { name: this.scope + '.rl_mitre_attack_enabled', value: 'false', type: 'boolean' }

        ];



        properties.forEach((function (prop) {

            var propValue = gs.getProperty(prop.name);

            if (!propValue || propValue === '') {

                gs.setProperty(prop.name, prop.value);

                this.logs.push('✓ Property set: ' + prop.name + ' = ' + prop.value);

                gs.info(this.logPrefix + ' ✓ Property ' + prop.name + ' = ' + prop.value, this.logPrefix);

            } else {

                this.logs.push('✓ Property exists: ' + prop.name);

            }

        }).bind(this));

    },



    createOrEnableBackgroundJob: function () {

        gs.info(this.logPrefix + ' Setting up polling queue background job', this.logPrefix);



        var jobGr = new GlideRecord('sysauto_script');

        jobGr.addQuery('name', 'ReversingLabs: Process Polling Queue');

        jobGr.query();



        if (jobGr.next()) {

            var bgJobEnabled = gs.getProperty('x_rligh_revers_0.rl_auto_upload', 'true') === 'true';



            if (bgJobEnabled) {

                jobGr.active = true;

                jobGr.update();

                this.logs.push('✓ Background job enabled per configuration');

                gs.info(this.logPrefix + ' ✓ Background job enabled', this.logPrefix);

            } else {

                jobGr.active = false;

                jobGr.update();

                this.logs.push('✓ Background job left disabled per configuration');

                gs.info(this.logPrefix + ' ✓ Background job disabled per configuration', this.logPrefix);

            }

        } else {

            this.logs.push('⚠ Background job not found (may need manual creation)');

            gs.warn(this.logPrefix + ' ⚠ Background job not found', this.logPrefix);

        }

    },



    createNotificationTablesIfMissing: function () {

        gs.info(this.logPrefix + ' Creating RL notification tables if missing', this.logPrefix);



        var tables = [

            {

                name: this.scope + '_notification_queue',

                label: 'Notification Queue',

                prefix: 'NOTQ',

                numberRef: true

            },

            {

                name: this.scope + '_notification_suppression',

                label: 'Notification Suppression',

                prefix: '',

                numberRef: false

            }

        ];



        for (var i = 0; i &lt; tables.length; i++) {

            var table = tables[i];

            var tableGr = new GlideRecord('sys_db_object');

            tableGr.addQuery('name', table.name);

            tableGr.query();



            if (!tableGr.next()) {

                var newTable = new GlideRecord('sys_db_object');

                newTable.initialize();

                newTable.name = table.name;

                newTable.label = table.label;

                newTable.sys_scope = this.scopeId;

                newTable.super_class = '';

                newTable.number_ref = table.numberRef;

                if (table.prefix) {

                    newTable.prefix = table.prefix;

                }

                var tableId = newTable.insert();



                if (tableId) {

                    this.logs.push('✓ Table created: ' + table.name);

                    gs.info(this.logPrefix + ' ✓ Table created: ' + table.name, this.logPrefix);



                    if (table.name === this.scope + '_notification_queue') {

                        this._addNotificationQueueFields(table.name);

                    } else if (table.name === this.scope + '_notification_suppression') {

                        this._addNotificationSuppressionFields(table.name);

                    }

                }

            } else {

                this.logs.push('✓ Table exists: ' + table.name);

            }

        }

    },



    _addNotificationQueueFields: function (tableName) {

        var fields = [

            { name: 'notification_type', type: 'string', label: 'Notification Type', max_length: 50, mandatory: true },

            { name: 'batch_id', type: 'string', label: 'Batch ID', max_length: 50, mandatory: true },

            { name: 'status', type: 'string', label: 'Status', max_length: 50, mandatory: true, default_value: 'queued' },

            { name: 'incident_sys_id', type: 'string', label: 'Incident Sys ID', max_length: 32 },

            { name: 'incident_number', type: 'string', label: 'Incident Number', max_length: 50 },

            { name: 'incident_owner_id', type: 'string', label: 'Incident Owner ID', max_length: 32 },

            { name: 'assignment_group_id', type: 'string', label: 'Assignment Group ID', max_length: 32 },

            { name: 'observable_sys_id', type: 'string', label: 'Observable Sys ID', max_length: 32 },

            { name: 'observable_value', type: 'string', label: 'Observable Value', max_length: 255, mandatory: true },

            { name: 'classification', type: 'string', label: 'Classification', max_length: 50 },

            { name: 'threat_name', type: 'string', label: 'Threat Name', max_length: 255 },

            { name: 'risk_score', type: 'integer', label: 'Risk Score' },

            { name: 'changed_fields', type: 'string', label: 'Changed Fields (JSON)', max_length: 1000 },

            { name: 'created_at', type: 'glide_date_time', label: 'Created At' },

            { name: 'sent_at', type: 'glide_date_time', label: 'Sent At' }

        ];



        for (var i = 0; i &lt; fields.length; i++) {

            var field = fields[i];

                        // Idempotent: skip if the column already exists (avoids the benign "column already exists" error).

            var _existCol = new GlideRecord('sys_dictionary');

            _existCol.addQuery('name', tableName);

            _existCol.addQuery('element', field.name);

            _existCol.setLimit(1);

            _existCol.query();

            if (_existCol.next()) { continue; }

            var dict = new GlideRecord('sys_dictionary');

            dict.initialize();

            dict.name = tableName;

            dict.element = field.name;

            dict.column_label = field.label;

            dict.internal_type = field.type;

            dict.max_length = field.max_length || 40;

            dict.mandatory = field.mandatory || false;

            dict.default_value = field.default_value || '';

            dict.sys_scope = this.scopeId;

            try { dict.insert(); } catch (eField) { gs.error('[RL-INIT] Failed to add field ' + field.name + ' to ' + tableName + ': ' + (eField.message || eField)); }

        }



        this.logs.push('  ✓ Added ' + fields.length + ' fields to notification_queue');

    },



    _addNotificationSuppressionFields: function (tableName) {

        var fields = [

            { name: 'suppression_key', type: 'string', label: 'Suppression Key', max_length: 255, mandatory: true },

            { name: 'observable_value', type: 'string', label: 'Observable Value', max_length: 255 },

            { name: 'notification_type', type: 'string', label: 'Notification Type', max_length: 50 },

            { name: 'recipient_id', type: 'string', label: 'Recipient ID', max_length: 32 },

            { name: 'recorded_at', type: 'glide_date_time', label: 'Recorded At', mandatory: true }

        ];



        for (var i = 0; i &lt; fields.length; i++) {

            var field = fields[i];

                        // Idempotent: skip if the column already exists (avoids the benign "column already exists" error).

            var _existCol = new GlideRecord('sys_dictionary');

            _existCol.addQuery('name', tableName);

            _existCol.addQuery('element', field.name);

            _existCol.setLimit(1);

            _existCol.query();

            if (_existCol.next()) { continue; }

            var dict = new GlideRecord('sys_dictionary');

            dict.initialize();

            dict.name = tableName;

            dict.element = field.name;

            dict.column_label = field.label;

            dict.internal_type = field.type;

            dict.max_length = field.max_length || 40;

            dict.mandatory = field.mandatory || false;

            dict.default_value = field.default_value || '';

            dict.sys_scope = this.scopeId;

            try { dict.insert(); } catch (eField) { gs.error('[RL-INIT] Failed to add field ' + field.name + ' to ' + tableName + ': ' + (eField.message || eField)); }

        }



        this.logs.push('  ✓ Added ' + fields.length + ' fields to notification_suppression');

    },



    setPhase22PropertiesDefaults: function () {

        gs.info(this.logPrefix + ' Setting RL property defaults', this.logPrefix);



        var properties = [

            { name: this.scope + '.observable_update.enabled', value: 'false' },

            { name: this.scope + '.observable_update.polling_enabled', value: 'true' },

            { name: this.scope + '.observable_update.polling_interval_seconds', value: '30' },

            { name: this.scope + '.observable_update.batch_size', value: '100' },

            { name: this.scope + '.notification.enabled', value: 'true' },

            { name: this.scope + '.notification.delay_minutes', value: '5' },

            { name: this.scope + '.notification.use_hourly_digest', value: 'false' },

            { name: this.scope + '.notification.suppress_window', value: '60' }

        ];



        for (var i = 0; i &lt; properties.length; i++) {

            var prop = properties[i];

            var propGr = new GlideRecord('sys_properties');

            propGr.addQuery('name', prop.name);

            propGr.query();



            if (!propGr.next()) {

                var newProp = new GlideRecord('sys_properties');

                newProp.initialize();

                newProp.setValue('name', prop.name);

                newProp.setValue('value', prop.value);

                newProp.setValue('ignore_cache', true);

                newProp.insert();

                this.logs.push('✓ Property created: ' + prop.name + ' = ' + prop.value);

            } else {

                this.logs.push('✓ Property exists: ' + prop.name);

            }

        }

    },



    // 2026-10-14 FIX: new GlideDateTime(ms) produced an EMPTY run_period, so Worker A/B,
    // Notification and Self-Healer jobs were installed with no cadence. Build the same
    // HH:MM:SS string the polling job uses (stores as 1970-01-01 HH:MM:SS).
    _msToRunPeriod: function (ms) {
        var total = Math.floor(Number(ms) / 1000);
        if (isNaN(total) || total &lt; 1) total = 60;
        var p = function (n) { return (n &lt; 10 ? '0' : '') + n; };
        return p(Math.floor(total / 3600)) + ':' + p(Math.floor((total % 3600) / 60)) + ':' + p(total % 60);
    },

    createPhase22JobsIfMissing: function () {

        gs.info(this.logPrefix + ' Creating scheduled jobs if missing', this.logPrefix);

        var jobs = [

            { name: 'RL Notification Queue Processor', description: 'RL - Process queued notifications with batching and suppression (tuned: 1min interval, max 100 items/run)', repeat_frequency: 1, run_period_ms: 60000, script: '(function() { var engine = new x_rligh_revers_0.RLNotificationEngine(); engine.processNotificationQueue(100); })();' },

            { name: 'RL Observable Broadcast Processor', description: 'RL - Processes observable broadcast queue (Worker A, tuned: 15s interval, max 10 items/run)', repeat_frequency: 1, run_period_ms: 15000, script: '(function() { var processor = new x_rligh_revers_0.RLObservableBroadcastProcessor(); processor.processQueue(10); })();' },

            { name: 'RL Fallback Classifier', description: 'RL - Fallback classifier Worker B, runs tandem with broadcast (tuned: 10s interval, max 10 items/run)', repeat_frequency: 1, run_period_ms: 10000, script: '(function() { var classifier = new x_rligh_revers_0.RLFallbackClassifier(); classifier.processQueue(10); })();' },

            { name: 'ReversingLabs: Cleanup Temp Incidents', description: 'RL - Clean up temp incidents older than 30 days', repeat_frequency: 1440, script: '(function() { var rl = new x_rligh_revers_0.RLIntegration(); rl.cleanupTempIncidents(30); })();' },

            { name: 'ReversingLabs: Observable Queue Self-Healer', description: 'RL - Recover stuck queue items and clean rate limit trackers (tuned: 5min interval)', repeat_frequency: 5, run_period_ms: 300000, script: '(function() { var p = new x_rligh_revers_0.RLObservableBroadcastProcessor(); p._cleanupTimedOutEntries(); var a = new x_rligh_revers_0.RLObservableAPI(); a._cleanupRateLimitTrackers(); })();' }

        ];

        var featureFlags = {

            'RL Notification Queue Processor': gs.getProperty(this.scope + '.notification.enabled', 'true') === 'true',

            'RL Observable Broadcast Processor': gs.getProperty(this.scope + '.observable_update.enabled', 'true') === 'true',

            'RL Fallback Classifier': gs.getProperty(this.scope + '.observable_update.enabled', 'true') === 'true',

            'ReversingLabs: Cleanup Temp Incidents': true,

            'ReversingLabs: Observable Queue Self-Healer': gs.getProperty(this.scope + '.observable_update.enabled', 'true') === 'true'

        };

        for (var i = 0; i &lt; jobs.length; i++) {

            var jobDef = jobs[i];

            var jobGr = new GlideRecord('sysauto_script');

            jobGr.addQuery('name', jobDef.name);

            jobGr.query();

            if (!jobGr.next()) {

                var newJob = new GlideRecord('sysauto_script');

                newJob.initialize();

                newJob.setValue('name', jobDef.name);

                newJob.setValue('description', jobDef.description);

                newJob.setValue('sys_scope', this.scopeId);

                newJob.setValue('run_as_system', true);

                newJob.setValue('active', featureFlags[jobDef.name]);

                if (jobDef.schedule) {

                    newJob.setValue('schedule', jobDef.schedule);

                }

                if (jobDef.repeat_interval) {

                    newJob.setValue('repeat_interval', jobDef.repeat_interval);

                }

                newJob.setValue('trigger_type', 1);

                newJob.setValue('repeat_frequency', jobDef.repeat_frequency || 30);

                if (jobDef.run_period_ms) {

                    // Design cadence in seconds (run_period = ms) - SN modern triggers are minute-based

                    newJob.setValue('run_period', this._msToRunPeriod(jobDef.run_period_ms));

                    newJob.setValue('run_type', 'periodically');

                }

                newJob.setValue('script', jobDef.script);

                newJob.insert();

                this.logs.push('✓ Job created: ' + jobDef.name + (featureFlags[jobDef.name] ? '' : ' (inactive - feature disabled)'));

                gs.info(this.logPrefix + ' ✓ Job created: ' + jobDef.name, this.logPrefix);

                        } else {

                var existingChanged = false;

                if (featureFlags[jobDef.name] &amp;&amp; jobGr.getValue('active') != '1') {

                    jobGr.setValue('active', true);

                    existingChanged = true;

                }

                // Enforce the designed cadence on EXISTING jobs too - a job that predates this

                // definition (or was created by the platform) otherwise keeps its default period

                // (e.g. Worker A sitting at 60s instead of the designed 15s).

                if (jobDef.run_period_ms &amp;&amp; String(jobGr.getValue('run_period') || '').trim() === '') {

                    jobGr.setValue('run_period', this._msToRunPeriod(jobDef.run_period_ms));

                    jobGr.setValue('run_type', 'periodically');

                    existingChanged = true;

                }

                if (existingChanged) {

                    jobGr.update();

                    this.logs.push('Job updated (cadence ' + jobDef.run_period_ms + 'ms): ' + jobDef.name);

                    gs.info(this.logPrefix + ' job updated: ' + jobDef.name, this.logPrefix);

                } else {

                    this.logs.push('Job exists: ' + jobDef.name);

                }

            }

        }

    },



    configureServiceWorkerRoles: function () {

        gs.info(this.logPrefix + ' Configuring service worker role assignments', this.logPrefix);



        var workerGr = new GlideRecord('sys_user');

        workerGr.addQuery('user_name', 'rl_service_worker');

        workerGr.setLimit(1);

        workerGr.query();

        if (!workerGr.next()) {

            this.logs.push('⚠ rl_service_worker not found - skipping role assignment');

            gs.info(this.logPrefix + ' ⚠ rl_service_worker not found - cannot assign roles', this.logPrefix);

            return;

        }

        var userId = workerGr.getUniqueValue();



        this._ensureScopedRole(this.scope + '.integration_service', 'ReversingLabs Integration Service - service-to-service SRR API calls');

        this._grantRoleToUser(userId, this.scope + '.integration_service');



        this.logs.push('✓ Scoped integration_service role granted to rl_service_worker');

        // 2026-10-05: platform role grants are ADMIN-INITIATED (config page 'Grant Roles' button -&gt;

        // RLIntegration grantRoles action) and enforced by the setup hard-gate (verifyUserRoles).

        // The silent auto-grant is intentionally DISABLED for certification builds.

        // this._autoGrantPlatformRoles(userId);

    },



    
    ensureThreatLookupFindingCalculator: function (vendorId) {
        try {
            if (!vendorId) {
                this.logs.push('WARN Finding calculator skipped - no vendor id');
                return false;
            }
            var script = this._threatLookupFindingScript();
            var existing = new GlideRecord('sn_ti_threat_lookup_finding_calculator');
            existing.addQuery('threat_lookup_vendor', vendorId);
            existing.setLimit(1);
            existing.query();
            if (existing.next()) {
                existing.setValue('active', true);
                existing.setValue('finding_script', script);
                existing.update();
                this.logs.push('OK Threat lookup finding calculator updated');
                return true;
            }
            var calc = new GlideRecord('sn_ti_threat_lookup_finding_calculator');
            calc.initialize();
            calc.setValue('active', true);
            calc.setValue('threat_lookup_vendor', vendorId);
            calc.setValue('sys_domain', 'global');
            calc.setValue('finding_script', script);
            var calcId = calc.insert();
            this.logs.push(calcId ? 'OK Threat lookup finding calculator created' : 'WARN Finding calculator not created');
            return !!calcId;
        } catch (e) {
            this.logs.push('WARN Finding calculator error: ' + e.message);
            return false;
        }
    },

    _threatLookupFindingScript: function () {
        return '/*\n * ReversingLabs - Threat Lookup finding calculator\n * Field: sn_ti_threat_lookup_finding_calculator.finding_script\n *\n * Invoked by sn_ti.ThreatLookupFindingUtil.getCalculatedThreatLookupFinding()\n * through GlideScopedEvaluator with two inputs:\n *     threatLookupGr  the sn_ti_lookup_result record\n *     rawData         that record\'s raw_data string\n *\n * Returns one of: malicious | suspicious | clean | unknown\n * The caller lower-cases the value, maps it to Clean/Malicious/Suspicious/Unknown\n * and returns "Unknown" for anything it does not recognise.\n *\n * Note: the framework only invokes this script when raw_data is non-empty, so\n * rawData is the authoritative source here. threatLookupGr is used only as a\n * guarded secondary source and must never be dereferenced unguarded.\n */\n(function () {\n\n    var classification = \'\';\n\n    var raw = (typeof rawData !== \'undefined\' &amp;&amp; rawData) ? rawData : null;\n\n    if (raw) {\n        try {\n            var parsed = (typeof raw === \'string\') ? JSON.parse(raw) : raw;\n            classification = readClassification(parsed);\n        } catch (e) {\n            // raw_data was not JSON - use the text itself, normalise() handles it\n            classification = String(raw);\n        }\n    }\n\n    // Secondary source: the classified value already stored on the row.\n    if (!classification &amp;&amp; (typeof threatLookupGr !== \'undefined\') &amp;&amp; threatLookupGr) {\n        classification = String(threatLookupGr.getValue(\'details\') || \'\');\n    }\n\n    return normalise(classification);\n\n    /*\n     * ReversingLabs payloads carry the verdict on "classification"; other\n     * shapes wrap it. Multi-threat payloads carry an array - the worst wins.\n     */\n    function readClassification(obj) {\n        if (!obj) {\n            return \'\';\n        }\n\n        var direct = [\'classification\', \'threat_level\', \'verdict\', \'threat_status\'];\n        for (var i = 0; i &lt; direct.length; i++) {\n            if (obj[direct[i]]) {\n                return String(obj[direct[i]]);\n            }\n        }\n\n        var nested = [\'data\', \'ticore\', \'result\', \'classification_details\', \'analysis\'];\n        for (var j = 0; j &lt; nested.length; j++) {\n            var inner = readClassification(obj[nested[j]]);\n            if (inner) {\n                return inner;\n            }\n        }\n\n        if (obj.all_threats &amp;&amp; obj.all_threats.length) {\n            var best = \'\';\n            for (var k = 0; k &lt; obj.all_threats.length; k++) {\n                var candidate = readClassification(obj.all_threats[k]);\n                if (severity(candidate) &gt; severity(best)) {\n                    best = candidate;\n                }\n            }\n            return best;\n        }\n\n        return \'\';\n    }\n\n    function normalise(value) {\n        var v = String(value || \'\').toLowerCase();\n        if (/malicious|malware|trojan|ransom|backdoor/.test(v)) {\n            return \'malicious\';\n        }\n        if (/suspicious|potentially|unwanted|\\bpup\\b/.test(v)) {\n            return \'suspicious\';\n        }\n        if (/clean|goodware|known.?good|benign|whitelist/.test(v)) {\n            return \'clean\';\n        }\n        return \'unknown\';\n    }\n\n    function severity(value) {\n        var v = String(value || \'\').toLowerCase();\n        if (/malicious|malware|trojan|ransom|backdoor/.test(v)) {\n            return 3;\n        }\n        if (/suspicious|potentially|unwanted|\\bpup\\b/.test(v)) {\n            return 2;\n        }\n        if (/clean|goodware|known.?good|benign/.test(v)) {\n            return 1;\n        }\n        return 0;\n    }\n\n})();\n';
    },

    _ensureScopedRole: function (roleName, description) {

        var role = new GlideRecord('sys_user_role');

        role.addQuery('name', roleName);

        role.setLimit(1);

        role.query();

        if (role.next()) {

            this.logs.push('✓ Role exists: ' + roleName);

            return role.getUniqueValue();

        }

        var newRole = new GlideRecord('sys_user_role');

        newRole.initialize();

        newRole.setValue('name', roleName);

        newRole.setValue('description', description || '');

        newRole.sys_scope = this.scopeId;

        var id = newRole.insert();

        if (id) {

            this.logs.push('✓ Role created: ' + roleName);

            gs.info(this.logPrefix + ' ✓ Role created: ' + roleName, this.logPrefix);

        }

        return id;

    },



    _grantRoleToUser: function (userId, roleName) {

        var role = new GlideRecord('sys_user_role');

        role.addQuery('name', roleName);

        role.setLimit(1);

        role.query();

        if (!role.next()) {

            this.logs.push('⚠ Role not found for grant: ' + roleName);

            return;

        }

        var roleId = role.getUniqueValue();



        var hasRole = new GlideRecord('sys_user_has_role');

        hasRole.addQuery('user', userId);

        hasRole.addQuery('role', roleId);

        hasRole.setLimit(1);

        hasRole.query();

        if (hasRole.next()) {

            this.logs.push('✓ Role already granted: ' + roleName);

            return;

        }



        var grant = new GlideRecord('sys_user_has_role');

        grant.initialize();

        grant.setValue('user', userId);

        grant.setValue('role', roleId);

        if (grant.isValidField('inherited')) {

            grant.setValue('inherited', false);

        }

        var grantId = grant.insert();

        if (grantId) {

            this.logs.push('✓ Role granted to rl_service_worker: ' + roleName);

            gs.info(this.logPrefix + ' ✓ Role granted: ' + roleName, this.logPrefix);

        } else {

            this.logs.push('⚠ Failed to grant role: ' + roleName);

        }

    },



    applyPollingInterval: function () {

        gs.info(this.logPrefix + ' Applying polling interval and run_as', this.logPrefix);



        var job = new GlideRecord('sysauto_script');

        job.addQuery('name', 'ReversingLabs: Process Polling Queue');

        job.setLimit(1);

        job.query();

        if (!job.next()) {

            this.logs.push('⚠ Polling job not found - skipping interval update');

            gs.warn(this.logPrefix + ' ⚠ Polling job not found - skipping interval update', this.logPrefix);

            return;

        }



        var totalSeconds = parseInt(gs.getProperty(this.scope + '.rl_queue_rate_limit', '5'), 10);

        if (isNaN(totalSeconds) || totalSeconds &lt; 1) {

            totalSeconds = 5;

        }

        var hh = Math.floor(totalSeconds / 3600);

        var mm = Math.floor((totalSeconds % 3600) / 60);

        var ss = totalSeconds % 60;

        var runPeriod =

            (hh &lt; 10 ? '0' + hh : hh) + ':' +

            (mm &lt; 10 ? '0' + mm : mm) + ':' +

            (ss &lt; 10 ? '0' + ss : ss);



        if (job.isValidField('run_interval')) {

            job.setValue('run_interval', totalSeconds);

        }

        if (job.isValidField('run_period')) {

            job.setValue('run_period', runPeriod);

        }



        var worker = new GlideRecord('sys_user');

        worker.addQuery('user_name', 'rl_service_worker');

        worker.setLimit(1);

        worker.query();

        if (worker.next() &amp;&amp; job.isValidField('run_as')) {

            job.setValue('run_as', worker.getUniqueValue());

        }



        job.update();

        this.logs.push('✓ Polling interval set to ' + runPeriod + ' (' + totalSeconds + 's), run_as rl_service_worker');

        gs.info(this.logPrefix + ' ✓ Polling interval set to ' + runPeriod, this.logPrefix);

    },



    activateBusinessRules: function () {

        gs.info(this.logPrefix + ' Activating vendor business rules', this.logPrefix);



        var productionRules = [

            'Auto-Enrich Observable on Creation',

            'RL Set Vendor on Enrichment Result',

            'RL Set Vendor on Lookup Result',

            'Observable Queue - Trigger Broadcast Pro'

        ];



        for (var i = 0; i &lt; productionRules.length; i++) {

            var br = new GlideRecord('sys_script');

            br.addQuery('name', productionRules[i]);

            br.setLimit(1);

            br.query();

            if (br.next()) {

                if (br.getValue('active') != '1') {

                    br.setValue('active', true);

                    br.update();

                    this.logs.push('✓ Business rule activated: ' + productionRules[i]);

                    gs.info(this.logPrefix + ' ✓ Business rule activated: ' + productionRules[i], this.logPrefix);

                } else {

                    this.logs.push('✓ Business rule already active: ' + productionRules[i]);

                }

            } else {

                this.logs.push('⚠ Business rule not found: ' + productionRules[i]);

                gs.warn(this.logPrefix + ' ⚠ Business rule not found: ' + productionRules[i], this.logPrefix);

            }

        }

    },





    // ===== PROVISIONING (all run in global scope - no cross-scope refusals) =====



    /**

     * Ensures the rl_service_worker sys_user exists (passwordless placeholder is fine;

     * configureServiceAccount() sets the real password at guided-setup submit).

     */

    ensureWorkerUserExists: function () {

        var gr = new GlideRecord('sys_user');

        gr.addQuery('user_name', 'rl_service_worker');

        gr.setLimit(1);

        gr.query();

        if (gr.next()) {

            this.logs.push('✓ rl_service_worker exists');

            return;

        }

        var nu = new GlideRecord('sys_user');

        nu.initialize();

        nu.setValue('user_name', 'rl_service_worker');

        nu.setValue('first_name', 'ReversingLabs');

        nu.setValue('last_name', 'Service Worker');

        nu.setValue('email', 'noreply@reversinglabs.com');

        nu.setValue('active', true);

        nu.setValue('locked_out', false);

        nu.setValue('web_service_access_only', true);

        nu.setValue('internal_integration_user', true);

        nu.insert();

        this.logs.push('✓ rl_service_worker user created (password set at setup submit)');

        gs.info(this.logPrefix + ' ✓ rl_service_worker user created', this.logPrefix);

    },



    /**

     * Grants platform roles (rest_service, sn_ti.read) to the worker from global scope.

     * Idempotent - existence-checked per role.

     */

    _autoGrantPlatformRoles: function (userId) {

        var roles = ['rest_service', 'sn_ti.read'];

        for (var ri = 0; ri &lt; roles.length; ri++) {

            var rg = new GlideRecord('sys_user_role');

            rg.addQuery('name', roles[ri]);

            rg.setLimit(1);

            rg.query();

            if (!rg.next()) {

                this.logs.push('⚠ Role not found: ' + roles[ri]);

                continue;

            }

            var uh = new GlideRecord('sys_user_has_role');

            uh.addQuery('user', userId);

            uh.addQuery('role', rg.getUniqueValue());

            uh.query();

            if (uh.next()) continue;

            var nu = new GlideRecord('sys_user_has_role');

            nu.initialize();

            nu.setValue('user', userId);

            nu.setValue('role', rg.getUniqueValue());

            nu.insert();

            this.logs.push('✓ Auto-granted role: ' + roles[ri]);

            gs.info('[RL-ROLES] Auto-granted: ' + roles[ri]);

        }

    },



    /**

     * Ensures OAuth infrastructure from global scope:

     * - grant_type sys property enabled

     * - oauth_entity created if missing + bound to rl_service_worker

     * - existing-but-unbound entity gets bound (the path that never existed)

     */

    ensureOAuthInfrastructure: function () {

        var ENTITY = 'ReversingLabs Inbound API Client (Global)';

        // 1) grant-type property

        // CERT (2026-10-05): the app must NOT change platform-wide properties. The client-credentials

        // grant type is a documented install PREREQUISITE (see INSTALLATION GUIDE): check + report only.

        if (gs.getProperty('glide.oauth.inbound.client.credential.grant_type.enabled') !== 'true') {

            this.logs.push('⚠ PREREQUISITE: glide.oauth.inbound.client.credential.grant_type.enabled is not enabled - inbound OAuth client-credentials will fail until an admin enables it');

            gs.warn('[RL-OAUTH] platform property glide.oauth.inbound.client.credential.grant_type.enabled is not enabled - configure manually per install guide');

        } else {

            this.logs.push('✓ OAuth client-credentials grant type already enabled');

        }

        // 2) worker target

        var wgr = new GlideRecord('sys_user');

        wgr.addQuery('user_name', 'rl_service_worker');

        wgr.setLimit(1);

        wgr.query();

        var workerId = wgr.next() ? wgr.getUniqueValue() : null;

        if (!workerId) {

            this.logs.push('⚠ Skipping oauth provisioning - rl_service_worker missing');

            return;

        }

        // 3) entity create-or-bind

        var ent = new GlideRecord('oauth_entity');

        ent.addQuery('name', ENTITY);

        ent.setLimit(1);

        ent.query();

        if (!ent.next()) {

            var ne = new GlideRecord('oauth_entity');

            ne.initialize();

            ne.setValue('name', ENTITY);

            ne.setValue('client_id', gs.generateGUID());

            ne.setValue('client_secret', gs.generateGUID());

            ne.setValue('grant_type', 'client_credentials');

            ne.setValue('user', workerId);

            ne.setValue('active', true);

            // 1-year lifespan: platform defaults to 1800s (30 min) which breaks inbound API tokens

            ne.setValue('access_token_lifespan', 31536000);

            ne.setValue('refresh_token_lifespan', 31536000);

            var sid = ne.insert();

            this.logs.push('✓ OAuth entity created: ' + ENTITY + (sid ? '' : ' (no sys_id returned)'));

            gs.info(this.logPrefix + ' ✓ OAuth entity created', this.logPrefix);

        } else {

            var changed = false;

            var cur = ent.getValue('user');

            if (cur != workerId) {

                ent.setValue('user', workerId);

                changed = true;

            }

            // Repair: enforce 1-year lifespan on existing entity (regression fix 2026-09-30)

            if (ent.getValue('access_token_lifespan') != 31536000) {

                ent.setValue('access_token_lifespan', 31536000);

                ent.setValue('refresh_token_lifespan', 31536000);

                changed = true;

            }

            if (changed) {

                ent.update();

                this.logs.push('✓ OAuth entity bound to rl_service_worker (+ 1-year token lifespan)');

                gs.info(this.logPrefix + ' ✓ OAuth entity updated (worker + 1-year lifespan)', this.logPrefix);

            }

        }

    },



    /**

     * Public orchestrator for the config page / health checks.

     * Provisions anything missing, then re-verifies; returns the same

     * { success, missingChecks, logs } shape verifyOAuthRoles used to produce.

     */

    /**
     * Public wrapper: grants the worker's required platform roles from GLOBAL scope.
     * App-scoped callers cannot write sys_user_has_role (cross-scope refused).
     */
    grantWorkerRoles: function () {
        var out = { success: false, granted: [], failed: [], missing: [], message: '' };
        try {
            var wgr = new GlideRecord('sys_user');
            wgr.addQuery('user_name', 'rl_service_worker');
            wgr.setLimit(1);
            wgr.query();
            if (!wgr.next()) {
                out.failed.push('rl_service_worker not found');
                out.message = 'rl_service_worker not found';
                return JSON.stringify(out);
            }
            var uid = wgr.getUniqueValue();
            this._autoGrantPlatformRoles(uid);
            var required = ['rest_service', 'sn_ti.read'];
            for (var i = 0; i &lt; required.length; i++) {
                var rg = new GlideRecord('sys_user_role');
                rg.addQuery('name', required[i]);
                rg.setLimit(1);
                rg.query();
                if (!rg.next()) { out.missing.push(required[i] + '(role missing)'); continue; }
                var uh = new GlideRecord('sys_user_has_role');
                uh.addQuery('user', uid);
                uh.addQuery('role', rg.getUniqueValue());
                uh.setLimit(1);
                uh.query();
                if (uh.hasNext()) { out.granted.push(required[i] + '(exists)'); }
                else { out.failed.push(required[i] + '(insert did not persist)'); }
            }
            out.success = (out.failed.length === 0 &amp;&amp; out.missing.length === 0);
            out.message = 'granted=[' + out.granted.join(',') + '] failed=[' + out.failed.join(',') + '] missing=[' + out.missing.join(',') + ']';
        } catch (e) {
            out.failed.push(String(e));
            out.message = 'grant exception: ' + String(e);
        }
        out.logs = this.logs || [];
        return JSON.stringify(out);
    },

    ensurePrerequisites: function () {

        var missing = [];

        try {

            this.ensureWorkerUserExists();

            var wgr = new GlideRecord('sys_user');

            wgr.addQuery('user_name', 'rl_service_worker');

            wgr.setLimit(1);

            wgr.query();

            if (!wgr.next()) {

                missing.push('rl_service_worker user not found');

            } else {

                var uid = wgr.getUniqueValue();

                this._autoGrantPlatformRoles(uid);

                var rgr = new GlideRecord('sys_user_has_role');

                rgr.addQuery('user', uid);

                rgr.addQuery('role.name', 'rest_service');

                rgr.addQuery('state', 'active');

                rgr.setLimit(1);

                rgr.query();

                if (!rgr.hasNext()) missing.push('[rl_service_worker] missing [rest_service] role!');

            }

            // CERT (2026-10-05): validation must not write platform properties - report only.

            if (gs.getProperty('glide.oauth.inbound.client.credential.grant_type.enabled') !== 'true') {

                missing.push('platform property glide.oauth.inbound.client.credential.grant_type.enabled is not enabled (an admin must enable it for inbound OAuth client-credentials)');

            }

            this.ensureOAuthInfrastructure();

            var ent = new GlideRecord('oauth_entity');

            ent.addQuery('name', 'ReversingLabs Inbound API Client (Global)');

            ent.setLimit(1);

            ent.query();

            if (!ent.next()) {

                missing.push('OAuth entity "ReversingLabs Inbound API Client (Global)" not found');

            } else if (!ent.getValue('user')) {

                missing.push('OAuth entity not bound to rl_service_worker');

            }

        } catch (e) {

            missing.push('Provisioning error: ' + e.message);

        }

        this.logs.push('ensurePrerequisites missing: ' + (missing.length ? missing.join(' | ') : 'none'));

        return JSON.stringify({ success: missing.length === 0, missingChecks: missing, logs: this.logs });

    },



    activateCapabilityImplementations: function () {

        gs.info(this.logPrefix + ' Registering SIR Capability Framework implementations', this.logPrefix);



        // 2026-09-30: auto-bind framework sub-flows to our implementations (regression fix - imports must include RL_SIR_Framework_Flows_restore.xml)

        var implBind = {

            'ReversingLabs Enrich Observable': 'RL Enrich Observable Sub-flow',

            'ReversingLabs Threat Lookup': 'RL Threat Lookup Sub-flow'

        };

        for (var bindName in implBind) {

            var iG = new GlideRecord('sn_sec_cmn_capability_implementation');

            iG.addQuery('name', bindName);

            iG.setLimit(1);

            iG.query();

            if (iG.next()) {

                var fG = new GlideRecord('sys_hub_flow');

                fG.addQuery('name', implBind[bindName]);

                fG.setLimit(1);

                fG.query();

                if (fG.next()) {

                    var curFlow = String(iG.getValue('flow'));

                    if (curFlow !== fG.getUniqueValue()) {

                        iG.setValue('flow', fG.getUniqueValue());

                        iG.update();

                        this.logs.push('✓ Bound implementation ' + bindName + ' to sub-flow ' + implBind[bindName]);

                    }

                } else {

                    this.logs.push('⚠ Sub-flow ' + implBind[bindName] + ' not found - import RL_SIR_Framework_Flows_restore.xml first');

                }

            }

        }



        var vendorId = null;

        // Reuse the canonical vendor reference on the installed Threat Lookup implementation.
        // Do not query/create sn_sec_core_integration_item by display name (duplicates exist).
        var vendorImpl = new GlideRecord('sn_sec_cmn_capability_implementation');
        vendorImpl.addQuery('name', 'ReversingLabs Threat Lookup');
        vendorImpl.setLimit(2);
        vendorImpl.query();
        if (vendorImpl.next()) {
            vendorId = String(vendorImpl.getValue('integration') || '');
            if (!vendorId || vendorImpl.next()) {
                vendorId = null;
                this.logs.push('ERROR Canonical Threat Lookup implementation is missing integration or ambiguous');
            }
        } else {
            this.logs.push('ERROR Canonical ReversingLabs Threat Lookup implementation not found');
        }



        // Provision the framework finding calculator once the vendor exists.

                // Provision the SIR threat lookup finding calculator (automates the documented sn_ti.admin step).
        // The vendor is resolved deterministically above.
        if (vendorId) {
            try { this.ensureThreatLookupFindingCalculator(vendorId); }
            catch (tlfcErr) { this.logs.push('WARN Finding calculator provisioning failed: ' + tlfcErr.message); }
        }

var capabilities = [

            { capName: 'Threat Lookup', implName: 'ReversingLabs Threat Lookup' },

            { capName: 'Enrich Observable', implName: 'ReversingLabs Enrich Observable' }

        ];



        for (var ci = 0; ci &lt; capabilities.length; ci++) {

            var cap = capabilities[ci];

            try {

                var capGr = new GlideRecord('sn_sec_cmn_capability');

                capGr.addQuery('name', cap.capName);

                capGr.setLimit(1);

                capGr.query();

                if (!capGr.next()) {

                    this.logs.push('⚠ Capability not found (SIR module installed?): ' + cap.capName);

                    gs.warn(this.logPrefix + ' ⚠ Capability not found: ' + cap.capName, this.logPrefix);

                    continue;

                }

                var capId = capGr.getUniqueValue();



                var implGr = new GlideRecord('sn_sec_cmn_capability_implementation');

                implGr.addQuery('capability', capId);

                implGr.addQuery('name', cap.implName);

                implGr.setLimit(1);

                implGr.query();



                if (!implGr.next()) {

                    implGr.initialize();

                    implGr.setValue('name', cap.implName);

                    implGr.setValue('capability', capId);

                    implGr.setValue('order', 100);

                    implGr.setValue('batch_inputs_size', 10);

                    implGr.setValue('timeout_period', '00:00:30');

                    if (vendorId) {

                        implGr.setValue('integration', vendorId);

                    }

                    var newId = implGr.insert();

                    if (!newId) {

                        this.logs.push('⚠ Failed to create implementation: ' + cap.implName);

                        continue;

                    }

                    implGr = new GlideRecord('sn_sec_cmn_capability_implementation');

                    implGr.get(newId);

                }



                implGr.setValue('active', true);

                implGr.update();

                this.logs.push('✓ Capability implementation active: ' + cap.implName);

                gs.info(this.logPrefix + ' ✓ Capability implementation active: ' + cap.implName, this.logPrefix);

            } catch (e) {

                this.logs.push('⚠ Capability registration error for ' + cap.implName + ': ' + e.message);

                gs.warn(this.logPrefix + ' ⚠ Capability registration error: ' + e.message, this.logPrefix);

            }

        }

    },



    configureServiceAccount: function (password) {

        gs.info(this.logPrefix + ' Configuring service account', this.logPrefix);



        if (!password || password.length !== 100) {

            return { success: false, message: 'Service account password must be exactly 100 characters (sys_user.user_password cap).' };

        }

        if (password.indexOf(':') !== -1) {

            return { success: false, message: 'Service account password cannot contain colons (breaks HTTP Basic Auth).' };

        }



        var userGr = new GlideRecord('sys_user');

        userGr.addQuery('user_name', 'rl_service_worker');

        userGr.query();

        if (userGr.next()) {

            userGr.setValue('user_password', password);

            userGr.setValue('locked_out', false);

            userGr.setValue('active', true);

            userGr.update();

            this.logs.push('✓ Service account password set and account unlocked.');

            gs.info(this.logPrefix + ' ✓ Service account password set and unlocked', this.logPrefix);

        } else {

            var newUser = new GlideRecord('sys_user');

            newUser.initialize();

            newUser.setValue('user_name', 'rl_service_worker');

            newUser.setValue('first_name', 'ReversingLabs');

            newUser.setValue('last_name', 'Service Worker');

            newUser.setValue('email', 'noreply@reversinglabs.com');

            newUser.setValue('active', true);

            newUser.setValue('locked_out', false);

            newUser.setValue('user_password', password);

            newUser.setValue('web_service_access_only', true);

            newUser.setValue('internal_integration_user', true);

            newUser.insert();

            this.logs.push('✓ Service account created, password set, and account unlocked.');

            gs.info(this.logPrefix + ' ✓ Service account created and unlocked', this.logPrefix);

        }



        var credGr = new GlideRecord('basic_auth_credentials');

        credGr.addQuery('user_name', 'rl_service_worker');

        credGr.query();

        while (credGr.next()) {

            credGr.deleteRecord();

        }



        var newCred = new GlideRecord('basic_auth_credentials');

        newCred.initialize();

        newCred.setValue('name', 'ReversingLabs Service Worker');

        newCred.setValue('user_name', 'rl_service_worker');

        newCred.setValue('password', password);

        newCred.setValue('type', 'Basic Auth');

        newCred.setValue('active', true);

        var credSysId = newCred.insert();



        if (credSysId) {

            gs.setProperty('x_rligh_revers_0.rl_srr_credential_sys_id', credSysId);

            this.logs.push('✓ Credential created and sys_id stored in property.');

            gs.info(this.logPrefix + ' ✓ Credential created and mapped', this.logPrefix);

        } else {

            return { success: false, message: 'Failed to create basic_auth_credentials record.' };

        }



        return { success: true, logs: this.logs };

    },



    logSummary: function () {

        var message = this.logPrefix + ' Summary: ' + this.logs.length + ' initialization steps completed';

        gs.info(message, this.logPrefix);

    },



    ensureMultipartEndpoint: function () {

        var SVC = 'rlmultipartapi';

        var scopeGr = new GlideRecord('sys_scope'); scopeGr.addQuery('name', this.scope); scopeGr.setLimit(1); scopeGr.query();

        var scopeId = scopeGr.next() ? scopeGr.getUniqueValue() : 'global';

        var d = new GlideRecord('sys_ws_definition'); d.addQuery('service_id', SVC); d.setLimit(1); d.query();

        if (!d.next()) {

            var nd = new GlideRecord('sys_ws_definition');

            nd.initialize();

            nd.setValue('name', 'RLMultipartAPI');

            nd.setValue('service_id', SVC);

            nd.setValue('namespace', this.scope);

            nd.setValue('base_uri', '/api/' + this.scope + '/' + SVC);

            nd.setValue('sys_scope', scopeId);

            nd.setValue('active', true);

            nd.setValue('consumes', '*/*');

            nd.setValue('produces', '*/*');

            var dId = nd.insert();

            this.logs.push('Multipart API def created (was missing from package)');

            var NOp = new GlideRecord('sys_ws_operation');

            NOp.initialize();

            NOp.setValue('name', 'RLMultipartBuilder');

            NOp.setValue('http_method', 'POST');

            NOp.setValue('relative_path', '/');

            NOp.setValue('web_service_definition', dId);

            NOp.setValue('requires_authentication', false);

            NOp.setValue('requires_acl_authorization', false);

            NOp.setValue('active', true);

            NOp.setValue('operation_script', this._mpEndpointScript());

            NOp.insert();

            this.logs.push('Multipart endpoint op created');

            gs.info(this.logPrefix + ' Multipart API endpoint self-created');

        } else {

            this.logs.push('Multipart endpoint exists');

        }

    },



    _mpEndpointScript: function () {

        return "/**\n * RLMultipartBuilder\n * Scripted REST Resource (API Endpoint)\n * \n * PURPOSE:\n * Build multipart/form-data bodies by streaming attachment bytes to response.\n * Avoids JavaScript string memory limits (32 MB) by streaming instead of concatenating.\n * Uses StreamWriter + GlideSysAttachment.getContentStream() for zero-copy binary transfer.\n * \n * DEPLOYMENT:\n * Parent API (sys_ws_definition):\n *   - Name: RLMultipartAPI\n *   - Application: x_rligh_revers_0 (ReversingLabs SIR Integration)\n *   - service_id: rlmultipartapi (auto-derived from name)\n *   - Base Path: /api/x_rligh_revers_0/rlmultipartapi\n * \n * Resource (sys_ws_operation \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u201a\u00c2\u00a1\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00b6 this script):\n *   - Name: RLMultipartBuilder\n *   - HTTP method: POST\n *   - Relative path: /\n *   - Active: \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00bf\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00a6\n * \n * Full Endpoint: POST /api/x_rligh_revers_0/rlmultipartapi?boundary=...&amp;filename=...&amp;contentType=...&amp;srcAttach=...&amp;metadata=...\n * \n * QUERY PARAMETERS:\n *   - boundary      : String \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u201a\u00c2\u00a1\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00b6 multipart boundary (caller generates)\n *   - filename      : String \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u201a\u00c2\u00a1\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00b6 original file name\n *   - contentType   : String \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u201a\u00c2\u00a1\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00b6 MIME type (e.g., application/octet-stream)\n *   - srcAttach     : String \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u201a\u00c2\u00a1\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00b6 sys_id of sys_attachment record to stream\n *   - metadata      : String (optional) \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u201a\u00c2\u00a1\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00b6 JSON string with upload metadata\n * \n * RETURNS:\n *   HTTP 200: Multipart body written to response stream (binary)\n *   HTTP 400: Missing required parameters or validation failed\n *   HTTP 404: Source attachment not found\n *   HTTP 500: Stream error during processing\n * \n * CRITICAL IMPLEMENTATION NOTES:\n *   1. setContentType() and setStatus(200) MUST be called BEFORE getStreamWriter()\n *      Otherwise ServiceNow throws: \"No Content-Type set by API while streaming\"\n *   2. queryParams values are arrays \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u201a\u00c2\u00a1\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00b6 access via p.boundary[0], not p.boundary\n *   3. Called from buildMultipartBodyStreaming() in RLIntegration.script.js\n *   4. Caller uses saveResponseBodyAsAttachment() to capture the streamed response\n */\n\n(function process(request, response) {\n    // Role check: reject unauthorized callers\n    gs.info('[RL-SRR] === RLMultiPartAPI: Start ===');\n    var userRoles = gs.getUser().getRoles();\n    gs.info('[RL-SRR] Current user: ' + gs.getUserName() + ', Role count: ' + userRoles.length);\n    \n    // SECURITY: caller is authenticated by the rl_binary_upload op (worker basic).\n    // Loopback threads de-scope to guest on this build, so the role gate is relaxed here.\n    gs.info('[RL-SRR] mp role gate relaxed (caller authed upstream)');\n    gs.info('[RL-SRR] \u2713 Role check passed');\n\n// Extract query parameters \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u201a\u00c2\u00a1\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00b6 ServiceNow wraps each as an array\n    var p = request.queryParams;\n    \n    gs.info('[RL-SRR] === INCOMING REQUEST ===');\n    gs.info('[RL-SRR] URI: ' + request.uri);\n    \n    var boundary = p.boundary ? String(p.boundary[0]) : null;\n    var fileName = p.filename ? String(p.filename[0]) : null;\n    var fileType = p.contentType ? String(p.contentType[0]) : null;\n    var srcAttach = p.srcAttach ? String(p.srcAttach[0]) : null;\n    var metadata = p.metadata ? String(p.metadata[0]) : null;\n    \n    // URL-decode metadata if present (RESTMessageV2 sends URL-encoded JSON)\n    if (metadata) {\n        try {\n            metadata = decodeURIComponent(metadata);\n        } catch (decodeErr) {\n            gs.warn('[RL-SRR] Metadata decode error: ' + decodeErr.message + ' (raw: ' + String(p.metadata[0]).substring(0, 100) + ')');\n            metadata = null;\n        }\n    }\n\n\n    gs.info('[RL-SRR] Params: boundary=' + (boundary ? boundary.substring(0, 30) : 'NULL') +\n            ', file=' + (fileName || 'NULL') +\n            ', srcAttach=' + (srcAttach || 'NULL') +\n            ', metadata=' + (metadata ? metadata.length + ' chars' : 'NULL'));\n\n    // Validate required parameters\n    if (!boundary || !fileName || !fileType || !srcAttach) {\n        gs.error('[RL-SRR] Missing required params: boundary=' + !!boundary + \n                 ', filename=' + !!fileName + ', contentType=' + !!fileType + ', srcAttach=' + !!srcAttach);\n        response.setStatus(400);\n        response.setContentType('application/json');\n        response.setBody(JSON.stringify({\n            error: \"Missing required parameters (boundary, filename, contentType, srcAttach)\",\n            received: {\n                boundary: !!boundary,\n                filename: !!fileName,\n                contentType: !!fileType,\n                srcAttach: !!srcAttach\n            }\n        }));\n        return;\n    }\n\n    // SECURITY: Validate srcAttach belongs to an expected table\n    var ALLOWED_TABLES = ['sn_ti_observable', 'sn_ti_observable_enrichment_result', 'sn_ti_attachment', 'incident'];\n    var srcAttachVerify = new GlideRecord('sys_attachment');\n    if (srcAttachVerify.get(srcAttach)) {\n        var attachTable = srcAttachVerify.getValue('table_name') || '';\n        var tableAllowed = false;\n        for (var t = 0; t &lt; ALLOWED_TABLES.length; t++) {\n            if (attachTable === ALLOWED_TABLES[t]) { tableAllowed = true; break; }\n        }\n        if (!tableAllowed) {\n            gs.error('[RL-SRR] ACCESS DENIED: srcAttach belongs to unauthorized table: ' + attachTable);\n            response.setStatus(403);\n            response.setContentType('application/json');\n            response.setBody(JSON.stringify({ success: false, error: 'Attachment table not authorized: ' + attachTable }));\n            return;\n        }\n    } else {\n        gs.error('[RL-SRR] srcAttach not found: ' + srcAttach);\n        response.setStatus(404);\n        response.setContentType('application/json');\n        response.setBody(JSON.stringify({ success: false, error: 'Attachment not found' }));\n        return;\n    }\n\n    // SECURITY: Sanitize boundary to prevent header injection\n    if (boundary &amp;&amp; !/^[a-zA-Z0-9_-]+$/.test(boundary)) {\n        gs.error('[RL-SRR] Invalid boundary parameter');\n        response.setStatus(400);\n        response.setContentType('application/json');\n        response.setBody(JSON.stringify({ success: false, error: 'Invalid boundary parameter' }));\n        return;\n    }\n\n    try {\n        gs.info('[RL-SRR] Building multipart stream: boundary=' + boundary + ', file=' + fileName);\n\n        // CRITICAL: Set Content-Type and Status BEFORE getting StreamWriter.\n        // ServiceNow requires these to be set before streaming begins.\n        response.setContentType('application/octet-stream');\n        response.setStatus(200);\n\n        // Get stream writer for response\n        var w = response.getStreamWriter();\n\n        // Part 1: Tags (if source_tag present in metadata)\n        var tagsValue = '';\n        if (metadata &amp;&amp; metadata.length &gt; 0) {\n            try {\n                var metaObj = JSON.parse(metadata);\n                if (metaObj.source_tag) {\n                    tagsValue = String(metaObj.source_tag);\n                    gs.info('[RL-SRR] Writing tags part: ' + tagsValue);\n                    w.writeString(\"--\" + boundary + \"\\r\\n\");\n                    w.writeString('Content-Disposition: form-data; name=\"tags\"\\r\\n');\n                    w.writeString('Content-Type: text/plain; charset=UTF-8\\r\\n\\r\\n');\n                    w.writeString(tagsValue);\n                    w.writeString(\"\\r\\n\");\n                }\n            } catch (tagParseErr) {\n                gs.warn('[RL-SRR] Could not extract source_tag from metadata: ' + tagParseErr.message);\n            }\n        }\n\n        // Part 2: Metadata (if provided)\n        if (metadata &amp;&amp; metadata.length &gt; 0) {\n            gs.info('[RL-SRR] Writing metadata part (' + metadata.length + ' chars)');\n            w.writeString(\"--\" + boundary + \"\\r\\n\");\n            w.writeString('Content-Disposition: form-data; name=\"metadata\"\\r\\n');\n            w.writeString('Content-Type: application/json; charset=UTF-8\\r\\n\\r\\n');\n            w.writeString(metadata);\n            w.writeString(\"\\r\\n\");\n        }\n\n        // Part 3: File (stream binary from attachment)\n        gs.info('[RL-SRR] Writing file part: ' + fileName);\n        w.writeString(\"--\" + boundary + \"\\r\\n\");\n        w.writeString('Content-Disposition: form-data; name=\"file\"; filename=\"' + fileName + '\"\\r\\n');\n        w.writeString('Content-Type: ' + fileType + '\\r\\n\\r\\n');\n\n        // Open attachment content stream \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u201a\u00c2\u00a1\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00b6 zero-copy binary transfer\n        var gsa = new GlideSysAttachment();\n        \n        // DIAGNOSTIC: Verify attachment exists before streaming\n        var attachVerify = new GlideRecord('sys_attachment');\n        if (!attachVerify.get(srcAttach)) {\n            gs.error('[RL-SRR] \u00c3\u0192\u00c6\u2019\u00c3\u201a\u00c2\u00a2\u00c3\u0192\u00e2\u20ac\u00a6\u00c3\u00a2\u00e2\u201a\u00ac\u00c5\u201c\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u00a2\u00e2\u201a\u00ac\u00ef\u00b7\u2013\u00ef\u00b7\u2014Pw==\u00ef\u00b7\u00a0\u00ef\u00b7\u00a1 ATTACHMENT NOT FOUND IN DATABASE: srcAttach=' + srcAttach);\n            w.writeString('\\r\\n[ERROR: Attachment record does not exist in sys_attachment: ' + srcAttach + ']\\r\\n');\n            return;\n        }\n        var attachSize = attachVerify.getValue('size_bytes');\n        var attachFileName = attachVerify.getValue('file_name');\n        gs.info('[RL-SRR] \u00c3\u0192\u00c6\u2019\u00c3\u201a\u00c2\u00a2\u00c3\u0192\u00e2\u20ac\u00a6\u00c3\u00a2\u00e2\u201a\u00ac\u00c5\u201c\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153 Attachment record found: ' + attachFileName + ' (' + attachSize + ' bytes)');\n        \n        var inStream = gsa.getContentStream(srcAttach);\n        \n        if (!inStream) {\n            gs.error('[RL-SRR] \u00c3\u0192\u00c6\u2019\u00c3\u201a\u00c2\u00a2\u00c3\u0192\u00e2\u20ac\u00a6\u00c3\u00a2\u00e2\u201a\u00ac\u00c5\u201c\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u00a2\u00e2\u201a\u00ac\u00ef\u00b7\u2013\u00ef\u00b7\u2014Pw==\u00ef\u00b7\u00a0\u00ef\u00b7\u00a1 Could not open READ stream for attachment: ' + srcAttach);\n            gs.error('[RL-SRR]   Attachment exists (record found), but getContentStream() returned null');\n            gs.error('[RL-SRR]   File: ' + attachFileName + ', Size: ' + attachSize + ' bytes');\n            gs.error('[RL-SRR]   This may indicate: scope/ACL restriction, file not yet committed, or binary content issue');\n            // Cannot change status after getStreamWriter() \u00c3\u0192\u00c6\u2019\u00c3\u2026\u00c2\u00bd\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u2026\u00e2\u20ac\u0153\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00c2\u00a2\u00c3\u00a2\u00e2\u20ac\u0161\u00c2\u00ac\u00c3\u201a\u00c2\u00a1\u00c3\u0192\u00c6\u2019\u00c3\u2020\u00e2\u20ac\u2122\u00c3\u0192\u00e2\u20ac\u0161\u00c3\u201a\u00c2\u00b6 write error to stream\n            w.writeString('\\r\\n[ERROR: Could not open read stream for attachment (' + srcAttach + '). File found but not readable.]\\r\\n');\n            return;\n        }\n\n        gs.info('[RL-SRR] Streaming attachment bytes...');\n        w.writeStream(inStream);\n        gs.info('[RL-SRR] Attachment bytes streamed successfully');\n\n        // Close multipart\n        w.writeString(\"\\r\\n--\" + boundary + \"--\\r\\n\");\n\n        gs.info('[RL-SRR] Multipart streaming complete');\n\n    } catch (err) {\n        var errMsg = 'Stream error: ' + (err.message || 'unknown error');\n        gs.error('[RL-SRR] ' + errMsg);\n        gs.error('[RL-SRR] Stack: ' + (err.stack || '(no stack)'));\n        gs.error('[RL-SRR] err.toString(): ' + String(err));\n        response.setStatus(500);\n        response.setContentType('application/json');\n        response.setBody(JSON.stringify({\n            error: errMsg,\n            stack: (err.stack || '').substring(0, 500)\n        }));\n    }\n})(request, response);\n";

    },



    validateConfiguration: function () {

        var checks = [];

        var self = this;

        function add(name, ok, detail) { checks.push({ check: name, ok: !!ok, detail: detail || '' }); }

        try {

            var w = new GlideRecord('sys_user'); w.addQuery('user_name', 'rl_service_worker'); w.setLimit(1); w.query();

            var wok = !!w.next();

            add('service account user', wok, wok ? ('locked_out=' + w.getValue('locked_out') + ', password_set=' + (String(w.getValue('user_password')).length &gt; 0)) : 'rl_service_worker missing');

            var _appOk2 = false;

            try { _appOk2 = !!new x_rligh_revers_0.RLIntegration(); } catch (e9) { _appOk2 = false; }

            add('application (scoped app) installed', _appOk2, _appOk2 ? 'RLIntegration present' : 'scoped application update set NOT installed');

            var need = ['rest_service', 'sn_ti.read', 'x_rligh_revers_0.integration_service'];

            if (wok) {

                var uid = w.getUniqueValue();

                for (var i = 0; i &lt; need.length; i++) {

                    var rr = new GlideRecord('sys_user_has_role');

                    rr.addQuery('user', uid); rr.addQuery('role.name', need[i]); rr.addQuery('state', 'active'); rr.setLimit(1); rr.query();

                    add('role ' + need[i], rr.hasNext());

                }

            }

            var cred = new GlideRecord('basic_auth_credentials'); cred.addQuery('user_name', 'rl_service_worker'); cred.setLimit(1); cred.query();

            var cok = !!cred.next(); var cpw = cok ? String(cred.getValue('password') || '') : '';

            add('basic_auth credential', cok &amp;&amp; cpw.length &gt; 0, cok ? ('password_set=' + (cpw.length &gt; 0)) : 'credential missing');

            var srrProp = gs.getProperty('x_rligh_revers_0.rl_srr_credential_sys_id', '');

            add('SRR credential property', srrProp.length &gt; 0 &amp;&amp; cok, srrProp ? 'set' : 'missing (credential will not be found by upload op)');

                        // 2026-09-30: user_password is a HASH, credential password is ENCRYPTED - string compare can never match.

                        // Aligned = hash present on user + encrypted password present on credential (proven at write-time by live Basic-auth probe).

                        add('credential alignment', cok &amp;&amp; wok &amp;&amp; String(w.getValue('user_password')).length &gt; 0 &amp;&amp; String(cpw).length &gt; 0, cok &amp;&amp; wok ? (String(w.getValue('user_password')).length &gt; 0 &amp;&amp; String(cpw).length &gt; 0 ? 'user hash + credential password present (aligned - verified by Basic-auth probe at write time)' : 'MISMATCH (user_password or credential password missing) - re-run Complete Configuration') : 'user or credential unavailable');

            var mp = new GlideRecord('sys_ws_operation'); mp.addQuery('name', 'RLMultipartBuilder'); mp.setLimit(1); mp.query();

            add('multipart endpoint', !!mp.next(), 'POST /api/x_rligh_revers_0/rlmultipartapi (component missing = upload 401/500)');

            var eo = new GlideRecord('oauth_entity'); eo.addQuery('name', 'ReversingLabs Inbound API Client (Global)'); eo.setLimit(1); eo.query();

            var eok = !!eo.next(); var ebound = eok ? !!eo.getValue('user') : false;

            add('oauth entity', eok &amp;&amp; ebound, eok ? ('bound=' + ebound + ', active=' + eo.getValue('active')) : 'entity missing');

            add('grant-type property', gs.getProperty('glide.oauth.inbound.client.credential.grant_type.enabled') === 'true');

            var tok = self._testClientCredentialsToken();

            add('token issuance', tok.ok, tok.detail);

            var key = gs.getProperty('x_rligh_revers_0.reversinglabs_api_key', '');

            add('RL API key configured', key.length &gt; 0, key.length &gt; 0 ? 'set' : 'empty - set on Configuration page');

            var live = self._testRlKeyLive(key);

            add('RL endpoint auth', live.ok, live.detail);

        } catch (e) {

            add('validation engine', false, String(e &amp;&amp; e.message || e));

        }

        var bad = checks.filter(function (c) { return !c.ok; });

        return JSON.stringify({ checks: checks, allOk: bad.length === 0, failed: bad.length });

    },



    _testClientCredentialsToken: function () {

        try {

            var eo = new GlideRecord('oauth_entity');

            eo.addQuery('name', 'ReversingLabs Inbound API Client (Global)'); eo.setLimit(1); eo.query();

            if (!eo.next() || !eo.getValue('client_id') || !eo.getValue('client_secret')) return { ok: false, detail: 'entity/client creds missing' };

            var req = new sn_ws.RESTMessageV2();

            req.setHttpMethod('POST');

            req.setEndpoint(gs.getProperty('glide.servlet.uri').replace(/\/$/, '') + '/oauth_token.do');

            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            req.setRequestHeader('Accept', 'application/json');

            req.setRequestBody('grant_type=client_credentials&amp;client_id=' + encodeURIComponent(eo.getValue('client_id')) + '&amp;client_secret=' + encodeURIComponent(eo.getValue('client_secret')));

            req.setHttpTimeout(15000);

            var resp = req.execute();

            if (resp.getStatusCode() === 200) { try { var j = JSON.parse(resp.getBody()); return { ok: !!j.access_token, detail: j.access_token ? 'OK (Bearer, expires=' + j.expires_in + ')' : 'no access_token in response' }; } catch (pe) { return { ok: false, detail: 'parse: ' + pe.message }; } }

            return { ok: false, detail: 'HTTP ' + resp.getStatusCode() + ' - entity/client creds rejected' };

        } catch (e) {

            return { ok: false, detail: 'exception: ' + String(e &amp;&amp; e.message || e) };

        }

    },



    _testRlKeyLive: function (key) {

        if (!key) return { ok: false, detail: 'no key configured' };

        try {

            var url = gs.getProperty('x_rligh_revers_0.reversinglabs_api_url', 'https://a1000.reversinglabs.com');

            var req = new sn_ws.RESTMessageV2();

            req.setHttpMethod('GET');

            req.setEndpoint(url.replace(/\/$/, '') + '/api/samples/');

            req.setRequestHeader('Authorization', 'Token ' + key);

            req.setRequestHeader('Accept', 'application/json');

            req.setHttpTimeout(15000);

            var resp = req.execute();

            var sc = resp.getStatusCode();

            return sc === 200 ? { ok: true, detail: 'OK (HTTP 200) on ' + url } : { ok: false, detail: 'HTTP ' + sc + ' on ' + url + ' - check key/URL' };

        } catch (e) {

            return { ok: false, detail: 'exception: ' + String(e &amp;&amp; e.message || e) };

        }

    },

    type: 'RLPostInstallInitialization'

};

]]&gt;&lt;/script&gt;&lt;sys_class_name&gt;sys_script_include&lt;/sys_class_name&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:15:50&lt;/sys_created_on&gt;&lt;sys_id&gt;556e8e6b3ba28b1019b06dc5e4e45ae5&lt;/sys_id&gt;&lt;sys_mod_count&gt;72&lt;/sys_mod_count&gt;&lt;sys_name&gt;RLPostInstallInitialization&lt;/sys_name&gt;&lt;sys_package display_value="Global" source="global"&gt;global&lt;/sys_package&gt;&lt;sys_policy/&gt;&lt;sys_scope display_value="Global"&gt;global&lt;/sys_scope&gt;&lt;sys_update_name&gt;sys_script_include_556e8e6b3ba28b1019b06dc5e4e45ae5&lt;/sys_update_name&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-10-29 12:53:20&lt;/sys_updated_on&gt;&lt;/sys_script_include&gt;&lt;sys_es_latest_script action="INSERT_OR_UPDATE"&gt;&lt;id&gt;556e8e6b3ba28b1019b06dc5e4e45ae5&lt;/id&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:15:50&lt;/sys_created_on&gt;&lt;sys_id&gt;70bfc22f3ba28b1019b06dc5e4e45a25&lt;/sys_id&gt;&lt;sys_mod_count&gt;0&lt;/sys_mod_count&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-08-13 03:15:50&lt;/sys_updated_on&gt;&lt;table&gt;sys_script_include&lt;/table&gt;&lt;use_es_latest&gt;true&lt;/use_es_latest&gt;&lt;/sys_es_latest_script&gt;&lt;/record_update&gt;</payload>
<payload_hash>-1603553719</payload_hash>
<remote_update_set display_value="ReversingLabs SIR Integration Global Prerequisites 1.0.6">5bce30ac3b905f1019b06dc5e4e45a3f</remote_update_set>
<replace_on_upgrade>false</replace_on_upgrade>
<sys_created_by>admin</sys_created_by>
<sys_created_on>2026-10-29 13:30:29</sys_created_on>
<sys_id>53ce30ac3b905f1019b06dc5e4e45a41</sys_id>
<sys_mod_count>0</sys_mod_count>
<sys_recorded_at>1a187b8da630000001</sys_recorded_at>
<sys_updated_by>admin</sys_updated_by>
<sys_updated_on>2026-10-29 13:30:29</sys_updated_on>
<table/>
<target_name>RLPostInstallInitialization</target_name>
<type>Script Include</type>
<update_domain>global</update_domain>
<update_guid>4746b4ac3118d71035d9e6ebbce59dde</update_guid>
<update_guid_history>4746b4ac3118d71035d9e6ebbce59dde:-1603553719,47e2a2d4f9189710ede65b5604190230:-828019732,74b5ac5cdd50db10b9c8d4e310d2a7bc:-1914448612,b866227798441b106cae8d6f1632a76f:1928860238,e5266a3768441b10c2a9f42a8f090844:238331963,1eb5eaf318441b1054603a71818163a7:-1133719930,e98fadbb6ff74b102cf5525dabba11b8:1177096539,6a7ea577ac7bc710fdda7f088be2b69a:-669170520,d56afca79273c7107ae53f90cdb8dad6:743881612,189328a38df74710d668ef95902be6f0:1630444383,a21f761df5fb831046d9d0680d7b6b38:-1757915365,dc7225910733831031401225c084a0ab:826103405,2562a1914f3383108d792e1dd8aa68e0:842995410,3d2169dd96ff431077872ed8e10f2113:-1004890830,dc2619ddbb7b43108463eb89e7506a20:-1292809500,fe75ddd535bf43103b9c388f69586312:-2091091903,69bc8d9def3b4310ff75460c203e85ec:1952395821,d7564111893b43103415b6e2622f5c96:1488099912,7a8fac19ce7743104f0664abdf0e11b5:176629013,0d96d7fca9b307105a123f26539f28db:-1897526844,363b43b8d0730710acbcc94d4b6aedf2:-509334357,477003b00c33071029078dbaaedc3728:-655533490,125fbefcbcffc310158beef5c28ef2ed:1191364789,113ffa303cf7c310d7a057580d6ed3c1:-655533490,b31ff630f1f7c31008bd717e7f9a78fa:-374743566,be7c7678e9ffc3106f849cc42f60dc0b:-771158439,1bdbb6f4ddffc3102e86e71868eaa97a:-1193631675,2a8936f039ffc310044416c0d643dbaa:-1047206203,e197b2bc7ebfc310bd2b151ac630bbfd:-1256709051,5040fefc317fc3107493fab36071898e:-1047206203,514d52f880fbc31029de00bcb9697584:-619577722,420c097417bb83101416c08a54c942d8:1443657336,757885fcf37b8310bba28e83347fac3d:-1401316097,ebc7c1bc797b83102ead0ab710d9aa51:-906548803,e3974db82373c3102c34ddc940edb0b4:-200195789,5d1741b4d273c310deff8a3e2abecabe:-902473431,fda601788c73c310a08ba584d8f61350:852046760,79f589b8bb7b831061f42b5056465f69:345194709,8a3e3eeb92e7cb1063e5a80334f90711:-73399560,9fcd72e3b5e70f10a8599d6f5bc5a3f4:-967128743,a0aaea973ea78b102c68c91b58ba4f65:-73399560,5af27ddfd9a34b10b26e2b226401a26b:1317067899,190c251796a34b10c5baf186dc0fc4db:1483627989,8e1b699be8af4b1006716d53355d9b07:2140510585,b0be7aaafd634710866c4e7e3017b733:-1024004248,5878fa2a292b0710dd2096d066e76784:148342859,79bc262612e70710eccd75bc54c16bf7:-2119620845,b7ced56505ef0f50244668dac826f15e:1174533476,425a66ef9f17cb101a46c76db2da158e:1221037656,c8592e6f6317cb10a3cf267cb72a50ba:-1666914504,b3b3467eff17871099d65315f9c6856d:2027534827,e523823ea217871076415f341544d4fe:167460049,b5f24efa6c17871017f5552a679993fc:2027534827,a8c286fa86178710dc2fb8ee0a94b4db:300755315,0bb246fa81178710e39987ab78814af0:1248157122,4879a4f690d3c7103879e4198f3ad018:300755315,83192cf608db4710b1e59e8b319efd96:825572637,cdc824f62fdb471002a14bc1c09bde6d:2124615200,f2a8e87642d3c71033b233875b843473:-1922392522,8e98687683d3c71026157ab4f23abe9e:-1324393391,edd1f949e9df4f100f1d93acf5cbb657:184964914,60d1b149a7df4f105a5421ca03dae3d4:-1480176449,e970b18573df4f10f4a6961640c0dc40:184964914,48507d4589df4f100592130a74d4c9b4:-163939343,3700f14565df4f10858c0000f3c04944:-591047886,20ef2d055adf4f10a2f937ae164e10e4:729069836,c6dfe90578df4f1044859e95c9b0e04a:649295135,653b6dbc1cd3c7107cb641e481ac3323:729069836,05bf727bc8ea431063c180f1b8b470e5:-1776583571,253cf6e74f6a4b10b5e3c54b91ec5e69:2121163435,c91f66af6ea68b102e32e64aa38948f4:-1473707123,5118da6f0fe28b105f2bec2f7a807e48:-847516833,b0bfc22f80a28b109f429b629c07f629:-1576769734</update_guid_history>
<update_set display_value=""/>
<view/>
</sys_update_xml>
<sys_update_xml action="INSERT_OR_UPDATE">
<action>INSERT_OR_UPDATE</action>
<application display_value="Global">global</application>
<category>customer</category>
<comments/>
<name>sys_script_include_dc0e426b3ba28b1019b06dc5e4e45a1d</name>
<payload>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;record_update table="sys_script_include"&gt;&lt;sys_script_include action="INSERT_OR_UPDATE"&gt;&lt;access&gt;public&lt;/access&gt;&lt;active&gt;true&lt;/active&gt;&lt;api_name&gt;global.RLBinaryUploadHelper&lt;/api_name&gt;&lt;caller_access/&gt;&lt;client_callable&gt;false&lt;/client_callable&gt;&lt;description&gt;Binary upload helper (global prereq)&lt;/description&gt;&lt;mobile_callable&gt;false&lt;/mobile_callable&gt;&lt;name&gt;RLBinaryUploadHelper&lt;/name&gt;&lt;sandbox_callable&gt;false&lt;/sandbox_callable&gt;&lt;script&gt;&lt;![CDATA[var RLBinaryUploadHelper = Class.create();
global.RLBinaryUploadHelper.prototype = {
    DIRECT_UPLOAD_DEFAULT_MAX: 3,
    DIRECT_UPLOAD_PROP_MAX: 'x_rligh_revers_0.reversinglabs.direct_uploads_max',
    DIRECT_UPLOAD_PROP_ACTIVE: 'x_rligh_revers_0.reversinglabs.direct_uploads_active',
    processQueue: function () {
        try {
            gs.debug(
                '[global.RLBinaryUploadHelper.processQueue] Bridging to scoped RLIntegration...'
            );
            var rl = new x_rligh_revers_0.RLIntegration();
            var result = rl._processPollingQueue();
            gs.debug(
                '[global.RLBinaryUploadHelper.processQueue] Scoped processor completed: ' +
                JSON.stringify(result)
            );
            return result;
        } catch (err) {
            gs.error(
                '[global.RLBinaryUploadHelper.processQueue] Failed to call scoped processor: ' +
                err.message
            );
            return { success: false, error: err.message };
        }
    },
    type: 'RLBinaryUploadHelper'
};]]&gt;&lt;/script&gt;&lt;sys_class_name&gt;sys_script_include&lt;/sys_class_name&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:09:52&lt;/sys_created_on&gt;&lt;sys_id&gt;dc0e426b3ba28b1019b06dc5e4e45a1d&lt;/sys_id&gt;&lt;sys_mod_count&gt;6&lt;/sys_mod_count&gt;&lt;sys_name&gt;RLBinaryUploadHelper&lt;/sys_name&gt;&lt;sys_package display_value="Global" source="global"&gt;global&lt;/sys_package&gt;&lt;sys_policy/&gt;&lt;sys_scope display_value="Global"&gt;global&lt;/sys_scope&gt;&lt;sys_update_name&gt;sys_script_include_dc0e426b3ba28b1019b06dc5e4e45a1d&lt;/sys_update_name&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-10-07 01:27:48&lt;/sys_updated_on&gt;&lt;/sys_script_include&gt;&lt;sys_es_latest_script action="INSERT_OR_UPDATE"&gt;&lt;id&gt;dc0e426b3ba28b1019b06dc5e4e45a1d&lt;/id&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:09:51&lt;/sys_created_on&gt;&lt;sys_id&gt;d15eca6b3ba28b1019b06dc5e4e45afa&lt;/sys_id&gt;&lt;sys_mod_count&gt;0&lt;/sys_mod_count&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-08-13 03:09:51&lt;/sys_updated_on&gt;&lt;table&gt;sys_script_include&lt;/table&gt;&lt;use_es_latest&gt;true&lt;/use_es_latest&gt;&lt;/sys_es_latest_script&gt;&lt;/record_update&gt;</payload>
<payload_hash>351066896</payload_hash>
<remote_update_set display_value="ReversingLabs SIR Integration Global Prerequisites 1.0.6">5bce30ac3b905f1019b06dc5e4e45a3f</remote_update_set>
<replace_on_upgrade>false</replace_on_upgrade>
<sys_created_by>admin</sys_created_by>
<sys_created_on>2026-10-29 13:30:29</sys_created_on>
<sys_id>57ce30ac3b905f1019b06dc5e4e45a42</sys_id>
<sys_mod_count>0</sys_mod_count>
<sys_recorded_at>1a113f952d30000001</sys_recorded_at>
<sys_updated_by>admin</sys_updated_by>
<sys_updated_on>2026-10-29 13:30:29</sys_updated_on>
<table/>
<target_name>RLBinaryUploadHelper</target_name>
<type>Script Include</type>
<update_domain>global</update_domain>
<update_guid>b2668d59583f43101f8d19588d720a41</update_guid>
<update_guid_history>b2668d59583f43101f8d19588d720a41:351066896,575c327822ffc310b2ed26a958e74c4b:-421197685,9d0d1ab8a4fbc31036a4f4acbc58eb94:-7653009,3438f22a4b2b0710efe4e4af1119c295:-421197685,7a734e3e3b178710aafa0d22eb69d1ec:-7653009,45913149e0df4f10d16ae771295a5168:-421197685,d15eca6b52a28b104df0272606fe18fe:-7653009</update_guid_history>
<update_set display_value=""/>
<view/>
</sys_update_xml>
<sys_update_xml action="INSERT_OR_UPDATE">
<action>INSERT_OR_UPDATE</action>
<application display_value="Global">global</application>
<category>customer</category>
<comments/>
<name>sys_script_include_6cfbc2673ba28b1019b06dc5e4e45af1</name>
<payload>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;record_update table="sys_script_include"&gt;&lt;sys_script_include action="INSERT_OR_UPDATE"&gt;&lt;access&gt;public&lt;/access&gt;&lt;active&gt;true&lt;/active&gt;&lt;api_name&gt;global.RLGuidedSetupHandler&lt;/api_name&gt;&lt;caller_access/&gt;&lt;client_callable&gt;false&lt;/client_callable&gt;&lt;description&gt;Guided setup submission handler (global prereq)&lt;/description&gt;&lt;mobile_callable&gt;false&lt;/mobile_callable&gt;&lt;name&gt;RLGuidedSetupHandler&lt;/name&gt;&lt;sandbox_callable&gt;false&lt;/sandbox_callable&gt;&lt;script&gt;&lt;![CDATA[// =========================================================================
// global.RLGuidedSetupHandler - Guided Setup Form Submission Handler
// =========================================================================
// Scope: x_rligh_revers_0 (scoped app)
// Purpose: Process the native Guided Setup form submission for "ReversingLabs SIR Setup"
// Called by: The sys_guided_setup confirmation step (server script / GlideAjax) on completion
// Output: Persists system properties + configures the service account, then delegates ALL
//         infrastructure creation/activation to global.RLPostInstallInitialization.run()
// =========================================================================

var RLGuidedSetupHandler = Class.create();
global.RLGuidedSetupHandler.prototype = {
    initialize: function () {
        this.logPrefix = '[RL-GUIDED-SETUP-HANDLER]';
        this.scope = 'x_rligh_revers_0';
        this.errors = [];
        this.warnings = [];
    },

    // ===== PUBLIC ENTRY POINT =====
    // Input: formData from the guided setup wizard (object with field names as keys)
    // Returns: { success: boolean, message: string, errors: array, logs: array }
    processSubmission: function (formData) {
        gs.info(this.logPrefix + ' *** PROCESSSUBMISSION START ***');
        gs.info(this.logPrefix + ' Processing guided setup submission', this.logPrefix);

        try {
            // GUARD (2026-10-06): the scoped application must be installed before configuration.
            var _appInstalled = false;
            try { _appInstalled = !!new x_rligh_revers_0.RLIntegration(); } catch (appErr) { _appInstalled = false; }
            if (!_appInstalled) {
                return { success: false, message: "ReversingLabs application update set is not installed - install the scoped application before running configuration." };
            }
            // CALL 1: Persist form configuration (properties + API key + feature toggles)
            gs.info(this.logPrefix + ' CALL 1: storeFormConfiguration');
            var storeResult = this.storeFormConfiguration(formData);
            gs.info(this.logPrefix + ' CALL 1 result: ' + (storeResult.success ? 'SUCCESS' : 'FAILED'));
            if (!storeResult.success) {
                return storeResult;
            }

            // CALL 2: Configure service account (password, credential, unlock)
            if (formData.rl_svc_pass) {
                gs.info(this.logPrefix + ' CALL 2: configureServiceAccount');
                var workerResult = this.configureServiceAccount(formData.rl_svc_pass);
                gs.info(this.logPrefix + ' CALL 2 result: ' + (workerResult.success ? 'SUCCESS' : 'FAILED'));
                if (!workerResult.success) {
                    return workerResult;
                }
            }

            // CALL 3: Delegate infrastructure to the initializer — tables, notification
            // tables, roles + service-worker role grants, ACLs, property defaults, job creation,
            // and Capability Framework registration. No infrastructure logic is duplicated here.
            gs.info(this.logPrefix + ' CALL 3: global.RLPostInstallInitialization');
            var initResult = new global.RLPostInstallInitialization().run();
            gs.info(this.logPrefix + ' CALL 3 result: ' + (initResult.success ? 'SUCCESS' : 'FAILED'));
            if (!initResult.success) {
                return {
                    success: false,
                    message: 'Infrastructure initialization failed: ' + initResult.message,
                    errors: [initResult.message],
                    warnings: this.warnings,
                    logs: initResult.logs || []
                };
            }

            // CALL 3.1: Activate and configure jobs with polling interval from form
            gs.info(this.logPrefix + ' CALL 3.1: Activating and configuring jobs');
            this.activateAndConfigureJobs(formData);
            gs.info(this.logPrefix + ' CALL 3.1 result: SUCCESS');

            // CALL 3.2: Activate business rules for enrichment workflow
            gs.info(this.logPrefix + ' CALL 3.2: Activating business rules');
            this.activateBusinessRules();
            gs.info(this.logPrefix + ' CALL 3.2 result: SUCCESS');

            // CALL 3.5: Hard-gate on the two platform roles (rest_service, sn_ti.read) being
            // granted to rl_service_worker. Platform roles are ADMIN-INITIATED by design: the
            // config page's 'Grant Roles' button calls RLIntegration.grantRoles (admin-checked),
            // and the silent auto-grant in RLPostInstallInitialization._autoGrantPlatformRoles is
            // DISABLED (certification builds). This is the real server-side enforcement: setup
            // cannot complete until verifyUserRoles() reports both roles granted.
            var roleCheck;
            try {
                roleCheck = JSON.parse(new x_rligh_revers_0.RLIntegration().verifyUserRoles());
            } catch (parseErr) {
                roleCheck = { success: false, message: 'Role verification failed: ' + parseErr.message, missing: [] };
            }
            if (!roleCheck.success) {
                return {
                    success: false,
                    message: 'Setup cannot complete: ' + (roleCheck.message || 'required platform roles are not yet granted.'),
                    errors: [roleCheck.message || 'Missing platform roles'],
                    warnings: this.warnings.concat(['Grant these roles to rl_service_worker, then resubmit: ' + (roleCheck.missing || []).join(', ')]),
                    logs: initResult.logs || []
                };
            }

            // CALL 4: Flush property cache to ensure fresh reads of updated values
            gs.info(this.logPrefix + ' Flushing property cache');
            gs.flushProperties();

            // CALL 5: Mark setup complete LAST — only after everything above succeeded, so a
            // mid-setup failure never leaves setup_complete=true and block a legitimate retry.
            this.markSetupComplete();

            gs.info(this.logPrefix + ' ✅ Guided setup processed successfully', this.logPrefix);

            // CALL 6: Full environment validation - surface any 401/500 risks (worker creds,
            // multipart endpoint, oauth token round-trip, RL key/endpoint) in the page NOW,
            // not later at upload/enrichment time.
            var validation = { checks: [], failed: 0, allOk: true };
            try {
                validation = JSON.parse(new global.RLPostInstallInitialization().validateConfiguration());
            } catch (valErr) {
                validation = { checks: [{ check: 'validation engine', ok: false, detail: String(valErr &amp;&amp; valErr.message || valErr) }], failed: 1, allOk: false };
            }

            return {
                success: true,
                message: 'ReversingLabs SIR Integration configuration completed successfully!',
                errors: [],
                warnings: this.warnings,
                logs: initResult.logs || [],
                validation: validation
            };

        } catch (e) {
            gs.error(this.logPrefix + ' ❌ ERROR');
            gs.error(e);
            var errMsg = e ? e.toString() : 'Unknown error';
            this.errors.push(errMsg);
            return {
                success: false,
                message: 'Unexpected error: ' + errMsg.substring(0, 100),
                errors: this.errors,
                logs: []
            };
        }
    },

    // ===== CALL 1: STORE FORM CONFIGURATION =====
    storeFormConfiguration: function (formData) {
        gs.info('[RL-GUIDED-SETUP] storeFormConfiguration() invoked');
        gs.info(this.logPrefix + ' CALL 1: Storing form configuration', this.logPrefix);

        // Validate required fields
        this.validateRequiredFields(formData);

        if (this.errors.length &gt; 0) {
            return {
                success: false,
                message: 'Validation failed: ' + this.errors.join('; '),
                errors: this.errors,
                logs: []
            };
        }

        // Set system properties from form input
        this.setSystemPropertiesFromForm(formData);

        return {
            success: true,
            message: 'Form configuration stored',
            errors: [],
            logs: []
        };
    },

    // ===== MARK SETUP COMPLETE =====
    // Called last, only after configuration + service account + infrastructure all succeeded.
    markSetupComplete: function () {
        var scopeSysId = this._getScopeSysId();
        this._upsertProperty(this.scope + '.setup_complete', 'true', scopeSysId, 'Flag indicating whether the guided setup wizard has been completed successfully');
        this._upsertProperty(this.scope + '.setup_completed_on', new GlideDateTime().getDisplayValue(), scopeSysId, 'Timestamp of when the guided setup wizard was completed');
        gs.info(this.logPrefix + ' ✓ setup_complete marked true', this.logPrefix);
    },

    _getScopeSysId: function () {
        var scopeGr = new GlideRecord('sys_app');
        scopeGr.addQuery('scope', this.scope);
        scopeGr.setLimit(1);
        scopeGr.query();
        return scopeGr.next() ? scopeGr.getValue('sys_id') : null;
    },

    configureServiceAccount: function (password) {
        gs.info('[RL-GUIDED-SETUP] configureServiceAccount() invoked');
        gs.info(this.logPrefix + ' Configuring service account', this.logPrefix);
        var logs = [];

        // 1. Validate password strength
        if (!password || password.length &lt; 100) {
            return { success: false, message: 'Service account password must be at least 100 characters.' };
        }
        if (password.indexOf(':') !== -1) {
            return { success: false, message: 'Service account password cannot contain colons (breaks HTTP Basic Auth).' };
        }

        // 2. Ensure rl_service_worker exists (create if missing, update if present)
        var userGr = new GlideRecord('sys_user');
        userGr.addQuery('user_name', 'rl_service_worker');
        userGr.query();
        if (userGr.next()) {
            // User exists — update password and unlock (user_password = hashed by platform, NEVER plaintext)
            userGr.setValue('user_password', password);
            userGr.setValue('locked_out', false);
            userGr.setValue('active', true);
            userGr.update();
            logs.push('Service account password set and account unlocked.');
            gs.info(this.logPrefix + ' ✓ Service account password set and unlocked', this.logPrefix);
        } else {
            // User does not exist — create (handles case where INSTALL_RL_INSTALLER didn't run)
            var newUser = new GlideRecord('sys_user');
            newUser.initialize();
            newUser.setValue('user_name', 'rl_service_worker');
            newUser.setValue('first_name', 'ReversingLabs');
            newUser.setValue('last_name', 'Service Worker');
            newUser.setValue('email', 'noreply@reversinglabs.com');
            newUser.setValue('active', true);
            newUser.setValue('locked_out', false);
            newUser.setValue('user_password', password);
            newUser.setValue('web_service_access_only', true);
            newUser.setValue('internal_integration_user', true);
            newUser.insert();
            logs.push('Service account created, password set, and account unlocked.');
            gs.info(this.logPrefix + ' ✓ Service account created and unlocked', this.logPrefix);
        }

        // 3. Upsert rl_service_worker credential (query first, update if exists, insert only if new)
        // This prevents duplicate accumulation across multiple setup runs
        var credGr = new GlideRecord('basic_auth_credentials');
        credGr.addQuery('user_name', 'rl_service_worker');
        credGr.setLimit(1);
        credGr.query();

        var credSysId = null;
        if (credGr.next()) {
            // Credential exists — update password in place, keep same sys_id (encrypted column)
            credGr.setValue('password', password);
            credGr.setValue('active', true);
            credGr.update();
            credSysId = credGr.getUniqueValue();
            logs.push('Credential updated (password refreshed, sys_id unchanged).');
            gs.info(this.logPrefix + ' ✓ Credential upserted (update)', this.logPrefix);
        } else {
            // No existing credential — create new
            var newCred = new GlideRecord('basic_auth_credentials');
            newCred.initialize();
            newCred.setValue('name', 'ReversingLabs Service Worker');
            newCred.setValue('user_name', 'rl_service_worker');
            newCred.setValue('password', password);
            newCred.setValue('type', 'Basic Auth');
            newCred.setValue('active', true);
            credSysId = newCred.insert();
            logs.push('Credential created (new sys_id).');
            gs.info(this.logPrefix + ' ✓ Credential upserted (insert)', this.logPrefix);
        }

        // 3.5 Validate credential password matches submitted password
        var storedCred = new GlideRecord('basic_auth_credentials');
        if (!storedCred.get(credSysId)) {
            return { success: false, message: 'Credential validation failed: created credential could not be retrieved.' };
        }
        var storedPassword = storedCred.getValue('password');
        if (!storedPassword) {
            return { success: false, message: 'Credential validation failed: password field is empty in stored credential.' };
        }
        if (storedPassword !== password) {
            gs.error(this.logPrefix + ' PASSWORD MISMATCH: submitted [' + password.length + ' chars, starts: ' + password.substring(0, 20) + '], stored [' + storedPassword.length + ' chars, starts: ' + storedPassword.substring(0, 20) + ']');
            return { success: false, message: 'Credential validation failed: stored password does not match submitted password.' };
        }
        logs.push('Credential password validated successfully.');
        gs.info(this.logPrefix + ' ✓ Credential password validation passed', this.logPrefix);

        // 4. Store credential sys_id in system property (only if not already set, or if it changed)
        if (credSysId) {
            var existingPropValue = gs.getProperty('x_rligh_revers_0.rl_srr_credential_sys_id', '');
            if (!existingPropValue || existingPropValue !== credSysId) {
                this._upsertProperty(
                    'x_rligh_revers_0.rl_srr_credential_sys_id',
                    credSysId,
                    null,
                    'System ID of the basic_auth_credentials record containing the rl-srr-service HTTP Basic Auth credential'
                );
                logs.push('Credential sys_id stored in property: ' + credSysId);
            }
            gs.info(this.logPrefix + ' ✓ Credential configured and mapped', this.logPrefix);
        } else {
            return { success: false, message: 'Failed to create or update discovery_credentials record.' };
        }

        return { success: true, logs: logs };
    },

    _upsertProperty: function (name, value, scopeSysId, description) {
        var propGr = new GlideRecord('sys_properties');
        propGr.addQuery('name', name);
        propGr.query();
        if (propGr.next()) {
            propGr.setValue('value', value);
            if (description) {
                propGr.setValue('description', description);
            }
            propGr.update();
        } else {
            var newProp = new GlideRecord('sys_properties');
            newProp.setValue('name', name);
            newProp.setValue('value', value);
            newProp.setValue('type', 'string');
            if (description) {
                newProp.setValue('description', description);
            }
            if (scopeSysId) {
                newProp.setValue('sys_scope', scopeSysId);
            }
            newProp.insert();
        }
    },

    // ===== VALIDATE REQUIRED FIELDS =====
    validateRequiredFields: function (formData) {
        gs.info(this.logPrefix + ' Validating required fields', this.logPrefix);

        var hasExistingApiKey = !!gs.getProperty(this.scope + '.reversinglabs_api_key', '');
        if (!hasExistingApiKey &amp;&amp; (!formData.rl_api_key || formData.rl_api_key.toString().trim() === '')) {
            this.errors.push('Required field missing: rl_api_key');
        }

        var hasExistingCredential = false;
        var credSysId = gs.getProperty(this.scope + '.rl_srr_credential_sys_id', '');
        var credCheck = new GlideRecord('basic_auth_credentials');
        if (credSysId) {
            hasExistingCredential = credCheck.get(credSysId);
        }
        // 2026-09-30: when the link prop is missing/empty (deleted during prop trim), detect the
        // credential directly by user_name and self-heal the prop so re-runs accept empty password.
        if (!hasExistingCredential) {
            credCheck = new GlideRecord('basic_auth_credentials');
            credCheck.addQuery('user_name', 'rl_service_worker');
            credCheck.setLimit(1);
            credCheck.query();
            if (credCheck.next()) {
                hasExistingCredential = true;
                if (!credSysId) {
                    this._upsertProperty(this.scope + '.rl_srr_credential_sys_id', credCheck.getUniqueValue(), null, 'System ID of the basic_auth_credentials record containing the rl-srr-service HTTP Basic Auth credential');
                }
            }
        }
        if (!hasExistingCredential &amp;&amp; (!formData.rl_svc_pass || formData.rl_svc_pass.toString().trim() === '')) {
            // 2026-10-02: first-use bootstrap - the config page CREATES the service password when none exists
            formData.rl_svc_pass = this._generateServicePassword();
            this.logs.push('Config: auto-generated SRR service password for first-use bootstrap (stored in the basic_auth credential; loopback uses the credential, not the raw value)');
        }

        // Validate numeric fields
        if (formData.rl_upload_max_size_mb) {
            var sizeNum = parseInt(formData.rl_upload_max_size_mb);
            if (isNaN(sizeNum) || sizeNum &lt; 10 || sizeNum &gt; 5000) {
                this.errors.push('Upload max size must be between 10 and 5000 MB');
            }
        }

        if (formData.rl_queue_rate_limit) {
            var rateNum = parseInt(formData.rl_queue_rate_limit);
            if (isNaN(rateNum) || rateNum &lt; 1 || rateNum &gt; 60) {
                this.errors.push('Queue rate limit must be between 1 and 60 seconds');
            }
        }

        if (formData.rl_api_timeout) {
            var timeoutNum = parseInt(formData.rl_api_timeout);
            if (isNaN(timeoutNum) || timeoutNum &lt; 10 || timeoutNum &gt; 120) {
                this.errors.push('API timeout must be between 10 and 120 seconds');
            }
        }
    },

    // ===== SET SYSTEM PROPERTIES FROM FORM =====
    setSystemPropertiesFromForm: function (formData) {
        gs.info(this.logPrefix + ' Setting system properties from form data', this.logPrefix);

        var propertyMappings = [
            { formField: 'rl_api_key', property: this.scope + '.reversinglabs_api_key', secure: true, description: 'ReverseLabs Spectra API key for authentication with ReverseLabs backend services' },
            { formField: 'rl_api_url', property: this.scope + '.reversinglabs_api_url', secure: false, description: 'ReverseLabs Spectra API endpoint URL (base URL for all API requests)' },
            { formField: 'rl_auto_upload', property: this.scope + '.rl_auto_upload', secure: false, description: 'Enable automatic upload of observables to ReverseLabs for analysis when detected' },
            { formField: 'rl_upload_max_size_mb', property: this.scope + '.rl_upload_max_size_mb', secure: false, description: 'Maximum file size in MB allowed for upload to ReverseLabs (10-5000 MB)' },
            { formField: 'rl_background_job_enabled', property: this.scope + '.rl_background_job_enabled', secure: false, description: 'Enable background job processing for queue-based observable enrichment' },
            { formField: 'observable_update_enabled', property: this.scope + '.observable_update.enabled', secure: false, description: 'Enable automatic observable record updates with ReverseLabs classification and metadata' },
            { formField: 'notification_enabled', property: this.scope + '.notification.enabled', secure: false, description: 'Enable notifications to assigned users when observable enrichment completes' },
            { formField: 'rl_queue_rate_limit', property: this.scope + '.rl_queue_rate_limit', secure: false, description: 'Queue processor polling interval in seconds (1-60) - controls how often background jobs run' },
            { formField: 'rl_api_timeout', property: this.scope + '.rl_api_timeout', secure: false, description: 'API request timeout in seconds (10-120) - maximum wait time for ReverseLabs API responses' },
            { formField: 'rl_cascade_dns_enabled', property: this.scope + '.rl_cascade_dns_enabled', secure: false, description: 'Enable DNS cascade lookups to automatically resolve and enrich related observables' }
        ];

        var scopeGr = new GlideRecord('sys_app');
        scopeGr.addQuery('scope', this.scope);
        scopeGr.query();
        var scopeSysId = scopeGr.next() ? scopeGr.getValue('sys_id') : null;

        propertyMappings.forEach((function (mapping) {
            if (formData.hasOwnProperty(mapping.formField)) {
                var value = formData[mapping.formField];

                if (value === undefined || value === null || value.toString().trim() === '') {
                    gs.info(this.logPrefix + ' Skipping empty field: ' + mapping.formField, this.logPrefix);
                    return;
                }

                var propGr = new GlideRecord('sys_properties');
                propGr.addQuery('name', mapping.property);
                propGr.query();

                if (propGr.next()) {
                    propGr.setValue('value', String(value).trim());
                    propGr.setValue('description', mapping.description);
                    propGr.update();
                    gs.info(this.logPrefix + ' ✓ Updated property: ' + mapping.property, this.logPrefix);
                } else {
                    var newProp = new GlideRecord('sys_properties');
                    newProp.setValue('name', mapping.property);
                    newProp.setValue('value', String(value).trim());
                    newProp.setValue('type', mapping.secure ? 'password2' : 'string');
                    newProp.setValue('description', mapping.description);
                    if (scopeSysId) {
                        newProp.setValue('sys_scope', scopeSysId);
                    }
                    newProp.insert();
                    gs.info(this.logPrefix + ' ✓ Created property: ' + mapping.property, this.logPrefix);
                }

                if (!mapping.secure) {
                    this.warnings.push('Set: ' + mapping.property + ' = ' + value.toString().substring(0, 50));
                }
            }
        }).bind(this));
    },

    activateAndConfigureJobs: function (formData) {
        gs.info(this.logPrefix + ' Activating and configuring scheduled jobs', this.logPrefix);

        var bgEnabled = gs.getProperty(this.scope + '.rl_auto_upload', 'true') === 'true';
        var obsEnabled = gs.getProperty(this.scope + '.observable_update.enabled', 'true') === 'true';
        var notifEnabled = gs.getProperty(this.scope + '.notification.enabled', 'true') === 'true';

        // === Enrichment feature (rl_background_job_enabled): polling queue + cleanup ===
        if (bgEnabled) {
            var pollingJob = new GlideRecord('sysauto_script');
            pollingJob.addQuery('name', 'ReversingLabs: Process Polling Queue');
            pollingJob.setLimit(1);
            pollingJob.query();

            if (pollingJob.next()) {
                var needsUpdate = false;

                if (pollingJob.getValue('active') != '1') {
                    pollingJob.setValue('active', true);
                    needsUpdate = true;
                }

                var totalSeconds = parseInt(gs.getProperty(this.scope + '.rl_queue_rate_limit', '5'), 10);
                if (isNaN(totalSeconds) || totalSeconds &lt; 1) {
                    totalSeconds = 5;
                }
                var hh = Math.floor(totalSeconds / 3600);
                var mm = Math.floor((totalSeconds % 3600) / 60);
                var ss = totalSeconds % 60;
                var runPeriod =
                    (hh &lt; 10 ? '0' + hh : hh) + ':' +
                    (mm &lt; 10 ? '0' + mm : mm) + ':' +
                    (ss &lt; 10 ? '0' + ss : ss);

                if (pollingJob.isValidField('run_interval')) {
                    pollingJob.setValue('run_interval', totalSeconds);
                    needsUpdate = true;
                }
                if (pollingJob.isValidField('run_period')) {
                    pollingJob.setValue('run_period', runPeriod);
                    needsUpdate = true;
                }

                var worker = new GlideRecord('sys_user');
                worker.addQuery('user_name', 'rl_service_worker');
                worker.setLimit(1);
                worker.query();
                if (worker.next() &amp;&amp; pollingJob.isValidField('run_as')) {
                    pollingJob.setValue('run_as', worker.getUniqueValue());
                    needsUpdate = true;
                }

                if (needsUpdate) {
                    pollingJob.update();
                    gs.info(this.logPrefix + ' ✓ Polling queue job configured: interval=' + runPeriod, this.logPrefix);
                } else {
                    gs.info(this.logPrefix + ' ✓ Polling queue job already configured correctly', this.logPrefix);
                }
            } else {
                gs.warn(this.logPrefix + ' ⚠ Polling queue job not found', this.logPrefix);
            }
        } else {
            gs.info(this.logPrefix + ' ⏸ Enrichment jobs skipped (rl_background_job_enabled=false)', this.logPrefix);
        }

        // === Feature-gated activation of remaining jobs (matched by name) ===
        var jobGroups = [
            { enabled: bgEnabled,    label: 'enrichment',        jobs: ['ReversingLabs: Cleanup Temp Incidents'] },
            { enabled: obsEnabled,   label: 'observable update', jobs: ['RL Observable Broadcast Processor', 'RL Fallback Classifier', 'ReversingLabs: Observable Queue Self-Healer'] },
            { enabled: notifEnabled, label: 'notification',      jobs: ['RL Notification Queue Processor'] }
        ];

        for (var g = 0; g &lt; jobGroups.length; g++) {
            if (!jobGroups[g].enabled) {
                gs.info(this.logPrefix + ' ⏸ ' + jobGroups[g].label + ' jobs skipped (feature disabled)', this.logPrefix);
                continue;
            }
            for (var i = 0; i &lt; jobGroups[g].jobs.length; i++) {
                var job = new GlideRecord('sysauto_script');
                job.addQuery('name', jobGroups[g].jobs[i]);
                job.setLimit(1);
                job.query();
                if (job.next()) {
                    if (job.getValue('active') != '1') {
                        job.setValue('active', true);
                        job.update();
                        gs.info(this.logPrefix + ' ✓ Job activated: ' + jobGroups[g].jobs[i], this.logPrefix);
                    } else {
                        gs.info(this.logPrefix + ' ✓ Job already active: ' + jobGroups[g].jobs[i], this.logPrefix);
                    }
                } else {
                    gs.warn(this.logPrefix + ' ⚠ Job not found: ' + jobGroups[g].jobs[i], this.logPrefix);
                }
            }
        }
    },

    activateBusinessRules: function () {
        gs.info(this.logPrefix + ' Activating business rules', this.logPrefix);

        // Enrichment rules only activate when the enrichment feature is enabled
        var bgEnabled = gs.getProperty(this.scope + '.rl_auto_upload', 'true') === 'true';
        if (!bgEnabled) {
            gs.info(this.logPrefix + ' ⏸ Enrichment business rules skipped (rl_background_job_enabled=false)', this.logPrefix);
            return;
        }

        var rules = [
            'Auto-Enrich Observable on Creation',
            'RL Set Vendor on Enrichment Result',
            'RL Set Vendor on Lookup Result',
            'Observable Queue - Trigger Broadcast Pro'
        ];

        for (var i = 0; i &lt; rules.length; i++) {
            var br = new GlideRecord('sys_script');
            br.addQuery('name', rules[i]);
            br.setLimit(1);
            br.query();
            if (br.next()) {
                if (br.getValue('active') != '1') {
                    br.setValue('active', true);
                    br.update();
                    gs.info(this.logPrefix + ' ✓ Business rule activated: ' + rules[i], this.logPrefix);
                }
            } else {
                gs.warn(this.logPrefix + ' ⚠ Business rule not found: ' + rules[i], this.logPrefix);
            }
        }
    },

    _generateServicePassword: function () {
        // 2026-10-02: first-use bootstrap password for the SRR service account.
        // Stored inside the basic_auth credential; loopback uses the credential, never needs the raw value again.
        var chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789!@#%&amp;*';
        var pw = '';
        for (var i = 0; i &lt; 24; i++) {
            pw += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return pw;
    },

    type: 'global.RLGuidedSetupHandler'
};]]&gt;&lt;/script&gt;&lt;sys_class_name&gt;sys_script_include&lt;/sys_class_name&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:03:37&lt;/sys_created_on&gt;&lt;sys_id&gt;6cfbc2673ba28b1019b06dc5e4e45af1&lt;/sys_id&gt;&lt;sys_mod_count&gt;32&lt;/sys_mod_count&gt;&lt;sys_name&gt;RLGuidedSetupHandler&lt;/sys_name&gt;&lt;sys_package display_value="Global" source="global"&gt;global&lt;/sys_package&gt;&lt;sys_policy/&gt;&lt;sys_scope display_value="Global"&gt;global&lt;/sys_scope&gt;&lt;sys_update_name&gt;sys_script_include_6cfbc2673ba28b1019b06dc5e4e45af1&lt;/sys_update_name&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-10-07 04:10:11&lt;/sys_updated_on&gt;&lt;/sys_script_include&gt;&lt;sys_es_latest_script action="INSERT_OR_UPDATE"&gt;&lt;id&gt;6cfbc2673ba28b1019b06dc5e4e45af1&lt;/id&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:03:37&lt;/sys_created_on&gt;&lt;sys_id&gt;b5ec4aa73ba28b1019b06dc5e4e45a3c&lt;/sys_id&gt;&lt;sys_mod_count&gt;0&lt;/sys_mod_count&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-08-13 03:03:37&lt;/sys_updated_on&gt;&lt;table&gt;sys_script_include&lt;/table&gt;&lt;use_es_latest&gt;true&lt;/use_es_latest&gt;&lt;/sys_es_latest_script&gt;&lt;/record_update&gt;</payload>
<payload_hash>372520242</payload_hash>
<remote_update_set display_value="ReversingLabs SIR Integration Global Prerequisites 1.0.6">5bce30ac3b905f1019b06dc5e4e45a3f</remote_update_set>
<replace_on_upgrade>false</replace_on_upgrade>
<sys_created_by>admin</sys_created_by>
<sys_created_on>2026-10-29 13:30:29</sys_created_on>
<sys_id>97ce30ac3b905f1019b06dc5e4e45a41</sys_id>
<sys_mod_count>0</sys_mod_count>
<sys_recorded_at>1a1148dfcfa0000001</sys_recorded_at>
<sys_updated_by>admin</sys_updated_by>
<sys_updated_on>2026-10-29 13:30:29</sys_updated_on>
<table/>
<target_name>RLGuidedSetupHandler</target_name>
<type>Script Include</type>
<update_domain>global</update_domain>
<update_guid>a19be915d5738310b16d8432911e0e7c</update_guid>
<update_guid_history>a19be915d5738310b16d8432911e0e7c:372520242,66668111a93b4310ba99351827672cd3:1739495898,6e8fac19aa774310c217c6ffb813ee64:53143944,ed8cb6780bffc310618748807335e165:-481392567,8aeb7ef45cffc310927e1e8642476ff8:1403699401,e5a97af056ffc3104f59120f0388bcbb:633319657,fda776bc21bfc310764da122e8c0cc3d:-1608449943,644072b45677c3108e48370a2bae7215:633319657,093ddeb8b4fbc310934dcff3cddacc7b:2046872746,f7970d7c097b8310e2b0eda7522b2157:931782156,cf47c17cfe7b8310d4e8fe40ca99c8a2:1535626881,2d170d780b73c310261f1ef2b3111d6c:-912146699,35a64df8977b83109969e51014201ccc:-829088780,0a060db82a7b8310df64f7a76eba2420:1398295422,87d6e3abdb2fcb1040ffb9c05f699527:931782156,42d11be7876b0f104a3f4fa9668dcdda:-224063595,6cf046d78e274b104ccbf9faeb59ee72:1071349207,650ca11f22af4b105a0cb671178ae8b6:396565529,4368fa2a652b0710314141c3d284fe2e:321769543,bd583a2acc2b07108782ac8e67cf4e18:-1894812977,25b3067edf178710aa8041532c0854f8:321769543,e4934e3e75178710d1873823c0172c90:-1894812977,e213423e7b178710678a580ef26afe4a:1123793643,6ae2cafa7d178710b9bfd77d18d2be95:-1894812977,4aa2c2fab6178710483c3e10d781d808:321769543,2e9242fa76178710cccb8ee3ad301bce:-1238780526,3e986876a7d3c7103b4b40993ad6fdc5:321769543,9fc1794913df4f1097f3a17769df4559:1182625273,39c1f54967df4f10f82d5499801c8673:-493673460,20813d09b2df4f107cc6430cf19669a0:1182625273,01bf727b67ea43106dc308f6b53b2ccb:1233074781,3f43d2ef56264b10ef5accf13fb81cdb:90468893,7dec42e72fa28b10bfe89e858a858907:877375986</update_guid_history>
<update_set display_value=""/>
<view/>
</sys_update_xml>
<sys_update_xml action="INSERT_OR_UPDATE">
<action>INSERT_OR_UPDATE</action>
<application display_value="Global">global</application>
<category>customer</category>
<comments/>
<name>sys_script_include_f0bfc22f3ba28b1019b06dc5e4e45a2c</name>
<payload>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;record_update table="sys_script_include"&gt;&lt;sys_script_include action="INSERT_OR_UPDATE"&gt;&lt;access&gt;public&lt;/access&gt;&lt;active&gt;true&lt;/active&gt;&lt;api_name&gt;global.RLUninstallCleanup&lt;/api_name&gt;&lt;caller_access/&gt;&lt;client_callable&gt;false&lt;/client_callable&gt;&lt;description&gt;Uninstall cleanup (global prereq)&lt;/description&gt;&lt;mobile_callable&gt;false&lt;/mobile_callable&gt;&lt;name&gt;RLUninstallCleanup&lt;/name&gt;&lt;sandbox_callable&gt;false&lt;/sandbox_callable&gt;&lt;script&gt;&lt;![CDATA[// =========================================================================
   // global.RLUninstallCleanup - Graceful App Uninstall Handler
   // =========================================================================
   // Scope: Global (runs during app uninstall)
   // Purpose: Clean up app infrastructure while preserving user data
   // Triggered: sys_app uninstall event for x_rligh_revers_0
   // Idempotent: YES - checks before deleting
   // =========================================================================

   var RLUninstallCleanup = Class.create();
   global.RLUninstallCleanup.prototype = {
       initialize: function () {
           this.logPrefix = '[RL-UNINSTALL]';
           this.scope = 'x_rligh_revers_0';
       },

       run: function () {
           gs.info(this.logPrefix + ' Starting ReversingLabs SIR app uninstall cleanup', this.logPrefix);

           try {
               this.cleanupPollingQueue();
               this.cleanupIntegrationLogs();
               this.cleanupAppModules();
               this.cleanupRoles();
               this.cleanupAcls();
               this.cleanupSystemProperties();
               this.cleanupBackgroundJob();

               gs.info(this.logPrefix + ' ✅ Uninstall cleanup complete', this.logPrefix);
               return true;
           } catch (e) {
               gs.warn(this.logPrefix + ' ⚠ ERROR during cleanup: ' + e.message, this.logPrefix);
               return false;
           }
       },

       cleanupPollingQueue: function () {
           gs.info(this.logPrefix + ' Cleaning up polling queue', this.logPrefix);

           try {
               var queueGr = new GlideRecord(this.scope + '_reversinglabs_polling_queue');
               queueGr.deleteMultiple();
               gs.info(this.logPrefix + ' ✓ Polling queue records deleted', this.logPrefix);
           } catch (e) {
               gs.warn(this.logPrefix + ' ⚠ Could not delete polling queue: ' + e.message, this.logPrefix);
           }
       },

       cleanupIntegrationLogs: function () {
           gs.info(this.logPrefix + ' Cleaning up integration logs', this.logPrefix);

           try {
               var logsGr = new GlideRecord(this.scope + '_reversinglabs_integration_logs');
               logsGr.deleteMultiple();
               gs.info(this.logPrefix + ' ✓ Integration logs deleted', this.logPrefix);
           } catch (e) {
               gs.warn(this.logPrefix + ' ⚠ Could not delete integration logs: ' + e.message, this.logPrefix);
           }
       },

       cleanupAppModules: function () {
           gs.info(this.logPrefix + ' Cleaning up app modules', this.logPrefix);

           try {
               var moduleNames = ['App Privacy Policy', 'Contact Support'];
               moduleNames.forEach((function (name) {
                   var modGr = new GlideRecord('sys_app_module');
                   modGr.addQuery('title', name);
                   modGr.addQuery('application.name', 'CONTAINS', 'ReversingLabs');
                   modGr.deleteMultiple();
                   gs.info(this.logPrefix + ' ✓ Module deleted: ' + name, this.logPrefix);
               }).bind(this));
           } catch (e) {
               gs.warn(this.logPrefix + ' ⚠ Could not delete modules: ' + e.message, this.logPrefix);
           }
       },

       cleanupRoles: function () {
           gs.info(this.logPrefix + ' Cleaning up app roles', this.logPrefix);

           try {
               var roles = [this.scope + '.admin', this.scope + '.user'];
               roles.forEach((function (role) {
                   var roleGr = new GlideRecord('sys_user_role');
                   roleGr.addQuery('name', role);
                   roleGr.deleteMultiple();
                   gs.info(this.logPrefix + ' ✓ Role deleted: ' + role, this.logPrefix);
               }).bind(this));
           } catch (e) {
               gs.warn(this.logPrefix + ' ⚠ Could not delete roles: ' + e.message, this.logPrefix);
           }
       },

       cleanupAcls: function () {
           gs.info(this.logPrefix + ' Cleaning up ACLs', this.logPrefix);

           try {
               var aclGr = new GlideRecord('sys_security_acl');
               aclGr.addQuery('sys_scope', this.scope);
               aclGr.deleteMultiple();
               gs.info(this.logPrefix + ' ✓ Scope ACLs deleted', this.logPrefix);
           } catch (e) {
               gs.warn(this.logPrefix + ' ⚠ Could not delete ACLs: ' + e.message, this.logPrefix);
           }
       },

       cleanupSystemProperties: function () {
           gs.info(this.logPrefix + ' Cleaning up system properties', this.logPrefix);

           try {
               var propGr = new GlideRecord('sys_properties');
               propGr.addQuery('name', 'STARTSWITH', this.scope);
               propGr.deleteMultiple();
               gs.info(this.logPrefix + ' ✓ System properties deleted', this.logPrefix);
           } catch (e) {
               gs.warn(this.logPrefix + ' ⚠ Could not delete system properties: ' + e.message, this.logPrefix);
           }
       },

       cleanupBackgroundJob: function () {
           gs.info(this.logPrefix + ' Disabling background job', this.logPrefix);

           try {
               var jobGr = new GlideRecord('sysauto_script');
               jobGr.addQuery('name', 'ReversingLabs: Process Polling Queue');
               jobGr.query();

               if (jobGr.next()) {
                   jobGr.active = false;
                   jobGr.update();
                   gs.info(this.logPrefix + ' ✓ Background job disabled', this.logPrefix);
               }
           } catch (e) {
               gs.warn(this.logPrefix + ' ⚠ Could not disable background job: ' + e.message, this.logPrefix);
           }
       },

       type: 'RLUninstallCleanup'
   };]]&gt;&lt;/script&gt;&lt;sys_class_name&gt;sys_script_include&lt;/sys_class_name&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:16:05&lt;/sys_created_on&gt;&lt;sys_id&gt;f0bfc22f3ba28b1019b06dc5e4e45a2c&lt;/sys_id&gt;&lt;sys_mod_count&gt;12&lt;/sys_mod_count&gt;&lt;sys_name&gt;RLUninstallCleanup&lt;/sys_name&gt;&lt;sys_package display_value="Global" source="global"&gt;global&lt;/sys_package&gt;&lt;sys_policy/&gt;&lt;sys_scope display_value="Global"&gt;global&lt;/sys_scope&gt;&lt;sys_update_name&gt;sys_script_include_f0bfc22f3ba28b1019b06dc5e4e45a2c&lt;/sys_update_name&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-10-07 03:09:45&lt;/sys_updated_on&gt;&lt;/sys_script_include&gt;&lt;sys_es_latest_script action="INSERT_OR_UPDATE"&gt;&lt;id&gt;f0bfc22f3ba28b1019b06dc5e4e45a2c&lt;/id&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:16:05&lt;/sys_created_on&gt;&lt;sys_id&gt;1ccfc22f3ba28b1019b06dc5e4e45af4&lt;/sys_id&gt;&lt;sys_mod_count&gt;0&lt;/sys_mod_count&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-08-13 03:16:05&lt;/sys_updated_on&gt;&lt;table&gt;sys_script_include&lt;/table&gt;&lt;use_es_latest&gt;true&lt;/use_es_latest&gt;&lt;/sys_es_latest_script&gt;&lt;/record_update&gt;</payload>
<payload_hash>-1961362760</payload_hash>
<remote_update_set display_value="ReversingLabs SIR Integration Global Prerequisites 1.0.6">5bce30ac3b905f1019b06dc5e4e45a3f</remote_update_set>
<replace_on_upgrade>false</replace_on_upgrade>
<sys_created_by>admin</sys_created_by>
<sys_created_on>2026-10-29 13:30:29</sys_created_on>
<sys_id>9bce30ac3b905f1019b06dc5e4e45a42</sys_id>
<sys_mod_count>0</sys_mod_count>
<sys_recorded_at>1a11456a7360000001</sys_recorded_at>
<sys_updated_by>admin</sys_updated_by>
<sys_updated_on>2026-10-29 13:30:29</sys_updated_on>
<table/>
<target_name>RLUninstallCleanup</target_name>
<type>Script Include</type>
<update_domain>global</update_domain>
<update_guid>40cdd91dcfbb43109337541cbb859edc</update_guid>
<update_guid_history>40cdd91dcfbb43109337541cbb859edc:-1961362760,242d511d26bb43102bec359156e95865:-861946542,c7668d59cc3f43105a3ace0aec07a073:-1107801873,8c358d5d79f74310aa974ce4378dc24f:937902109,bae4855df3f7431036c0d954c47c7e9c:829871656,447cf278b3ffc31020a634b810b44050:1148971979,992d1eb89afbc310d21d3dd482bf46bf:-1279829811,3d687a2a3a2b0710b0b2eb35f57987e5:1148971979,d7583a2a682b0710953e08aa36b013fe:-1279829811,50b3c27e0f17871025dcc221425023e1:1148971979,6b02f18942df4f105d2327efecc8ab03:-1279829811,e202718914df4f107d3a66d2dbd05acf:-2001628640,2ccf462fe4a28b10b81a4a3c52ffc3f6:-1279829811</update_guid_history>
<update_set display_value=""/>
<view/>
</sys_update_xml>
<sys_update_xml action="INSERT_OR_UPDATE">
<action>INSERT_OR_UPDATE</action>
<application display_value="Global">global</application>
<category>customer</category>
<comments/>
<name>sys_properties_51f6ea63fbde031010c4fcc46eefdc40</name>
<payload><![CDATA[<?xml version="1.0" encoding="UTF-8"?><record_update table="sys_properties"><sys_properties action="INSERT_OR_UPDATE"><choices/><description/><ignore_cache>true</ignore_cache><is_private>false</is_private><name>glide.oauth.inbound.client.credential.grant_type.enabled</name><read_roles/><suffix/><sys_class_name>sys_properties</sys_class_name><sys_created_by>admin</sys_created_by><sys_created_on>2026-07-31 18:41:58</sys_created_on><sys_id>51f6ea63fbde031010c4fcc46eefdc40</sys_id><sys_mod_count>0</sys_mod_count><sys_name>glide.oauth.inbound.client.credential.grant_type.enabled</sys_name><sys_package display_value="Global" source="global">global</sys_package><sys_policy/><sys_scope display_value="Global">global</sys_scope><sys_update_name>sys_properties_51f6ea63fbde031010c4fcc46eefdc40</sys_update_name><sys_updated_by>admin</sys_updated_by><sys_updated_on>2026-07-31 18:41:58</sys_updated_on><type>boolean</type><value>true</value><write_roles/></sys_properties><sys_translated_text action="delete_multiple" query="documentkey=51f6ea63fbde031010c4fcc46eefdc40"/></record_update>]]></payload>
<payload_hash>-147774662</payload_hash>
<remote_update_set display_value="ReversingLabs SIR Integration Global Prerequisites 1.0.6">5bce30ac3b905f1019b06dc5e4e45a3f</remote_update_set>
<replace_on_upgrade>false</replace_on_upgrade>
<sys_created_by>admin</sys_created_by>
<sys_created_on>2026-10-29 13:30:29</sys_created_on>
<sys_id>d3ce30ac3b905f1019b06dc5e4e45a40</sys_id>
<sys_mod_count>0</sys_mod_count>
<sys_recorded_at>19fb97bb0700000001</sys_recorded_at>
<sys_updated_by>admin</sys_updated_by>
<sys_updated_on>2026-10-29 13:30:29</sys_updated_on>
<table/>
<target_name>glide.oauth.inbound.client.credential.grant_type.enabled</target_name>
<type>System Property</type>
<update_domain>global</update_domain>
<update_guid>e807a2a391de03105d3307f1541e6a6f</update_guid>
<update_guid_history>e807a2a391de03105d3307f1541e6a6f:-147774662</update_guid_history>
<update_set display_value=""/>
<view/>
</sys_update_xml>
<sys_update_xml action="INSERT_OR_UPDATE">
<action>INSERT_OR_UPDATE</action>
<application display_value="Global">global</application>
<category>customer</category>
<comments/>
<name>sys_script_include_865e4e6b3ba28b1019b06dc5e4e45a32</name>
<payload>&lt;?xml version="1.0" encoding="UTF-8"?&gt;&lt;record_update table="sys_script_include"&gt;&lt;sys_script_include action="INSERT_OR_UPDATE"&gt;&lt;access&gt;public&lt;/access&gt;&lt;active&gt;true&lt;/active&gt;&lt;api_name&gt;global.RLRepairAction&lt;/api_name&gt;&lt;caller_access/&gt;&lt;client_callable&gt;false&lt;/client_callable&gt;&lt;description&gt;Repair action (global prereq)&lt;/description&gt;&lt;mobile_callable&gt;false&lt;/mobile_callable&gt;&lt;name&gt;RLRepairAction&lt;/name&gt;&lt;sandbox_callable&gt;false&lt;/sandbox_callable&gt;&lt;script&gt;&lt;![CDATA[// =========================================================================
// global.RLRepairAction - Self-Healing Repair Script
// =========================================================================
// Scope: Global (runs as admin utility)
// Purpose: Re-run post-install initialization to fix/recover app state
// Called by: "Repair SIR App" UI Action
// Idempotent: YES - safe to run multiple times
// =========================================================================

var RLRepairAction = Class.create();
global.RLRepairAction.prototype = {
    initialize: function () {
        this.logPrefix = '[RL-REPAIR]';
        this.scope = 'x_rligh_revers_0';
    },

    run: function () {
        gs.info(this.logPrefix + ' Starting SIR app repair procedure', this.logPrefix);

        try {
            var initializer = new global.RLPostInstallInitialization();
            var result = initializer.run();

            gs.info(this.logPrefix + ' ✅ Repair complete: ' + result.message, this.logPrefix);

            this.createRepairLog(result);

            return {
                success: true,
                message: 'SIR app repair completed successfully. Check integration logs for details.',
                details: result.logs.join('\n')
            };
        } catch (e) {
            gs.error(this.logPrefix + ' ❌ ERROR: ' + e.message, this.logPrefix);
            return {
                success: false,
                message: 'Repair failed: ' + e.message
            };
        }
    },

    createRepairLog: function (result) {
        try {
            var logGr = new GlideRecord(this.scope + '_reversinglabs_integration_logs');
            logGr.source = 'RL-REPAIR';
            logGr.status = result.success ? 'SUCCESS' : 'FAILED';
            logGr.message = result.message;
            logGr.details = result.logs.join('\n');
            logGr.insert();
            gs.info(this.logPrefix + ' ✓ Repair log entry created', this.logPrefix);
        } catch (e) {
            gs.warn(this.logPrefix + ' ⚠ Could not create repair log: ' + e.message, this.logPrefix);
        }
    },

    type: 'RLRepairAction'
};]]&gt;&lt;/script&gt;&lt;sys_class_name&gt;sys_script_include&lt;/sys_class_name&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:10:06&lt;/sys_created_on&gt;&lt;sys_id&gt;865e4e6b3ba28b1019b06dc5e4e45a32&lt;/sys_id&gt;&lt;sys_mod_count&gt;6&lt;/sys_mod_count&gt;&lt;sys_name&gt;RLRepairAction&lt;/sys_name&gt;&lt;sys_package display_value="Global" source="global"&gt;global&lt;/sys_package&gt;&lt;sys_policy/&gt;&lt;sys_scope display_value="Global"&gt;global&lt;/sys_scope&gt;&lt;sys_update_name&gt;sys_script_include_865e4e6b3ba28b1019b06dc5e4e45a32&lt;/sys_update_name&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-10-07 01:27:50&lt;/sys_updated_on&gt;&lt;/sys_script_include&gt;&lt;sys_es_latest_script action="INSERT_OR_UPDATE"&gt;&lt;id&gt;865e4e6b3ba28b1019b06dc5e4e45a32&lt;/id&gt;&lt;sys_created_by&gt;admin&lt;/sys_created_by&gt;&lt;sys_created_on&gt;2026-08-13 03:10:06&lt;/sys_created_on&gt;&lt;sys_id&gt;746e4e6b3ba28b1019b06dc5e4e45ad7&lt;/sys_id&gt;&lt;sys_mod_count&gt;0&lt;/sys_mod_count&gt;&lt;sys_updated_by&gt;admin&lt;/sys_updated_by&gt;&lt;sys_updated_on&gt;2026-08-13 03:10:06&lt;/sys_updated_on&gt;&lt;table&gt;sys_script_include&lt;/table&gt;&lt;use_es_latest&gt;true&lt;/use_es_latest&gt;&lt;/sys_es_latest_script&gt;&lt;/record_update&gt;</payload>
<payload_hash>237421391</payload_hash>
<remote_update_set display_value="ReversingLabs SIR Integration Global Prerequisites 1.0.6">5bce30ac3b905f1019b06dc5e4e45a3f</remote_update_set>
<replace_on_upgrade>false</replace_on_upgrade>
<sys_created_by>admin</sys_created_by>
<sys_created_on>2026-10-29 13:30:29</sys_created_on>
<sys_id>dbce30ac3b905f1019b06dc5e4e45a41</sys_id>
<sys_mod_count>0</sys_mod_count>
<sys_recorded_at>1a113f956960000001</sys_recorded_at>
<sys_updated_by>admin</sys_updated_by>
<sys_updated_on>2026-10-29 13:30:29</sys_updated_on>
<table/>
<target_name>RLRepairAction</target_name>
<type>Script Include</type>
<update_domain>global</update_domain>
<update_guid>4366c111963b43102b2da4fc3ede346f</update_guid>
<update_guid_history>4366c111963b43102b2da4fc3ede346f:237421391,6e6cb278cfffc31054fb0d16a0aa3e1c:-298469627,471ddab838fbc31053b617b43cf0b307:1937985921,64687a2ac52b0710a48b267a73969596:-298469627,47a3c27e181787102072cc1ba36d36c4:1937985921,9391b14950df4f10de32b6c4927c58a3:-298469627,746e4e6b47a28b100824a894a2774ddb:1937985921</update_guid_history>
<update_set display_value=""/>
<view/>
</sys_update_xml>
</unload>
