@trillboards/edge-sdk 0.2.260 → 0.2.263
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/deploy/windows/ci/test-published-install.ps1 +10 -1
- package/dist/CloudSensingManager.d.ts +36 -0
- package/dist/CloudSensingManager.d.ts.map +1 -1
- package/dist/CloudSensingManager.js +147 -20
- package/dist/CloudSensingManager.js.map +1 -1
- package/dist/EdgeAgent.js +1 -1
- package/dist/VideoSegmentUploader.d.ts +4 -0
- package/dist/VideoSegmentUploader.d.ts.map +1 -1
- package/dist/VideoSegmentUploader.js +21 -1
- package/dist/VideoSegmentUploader.js.map +1 -1
- package/dist/autoSense.d.ts +5 -4
- package/dist/autoSense.d.ts.map +1 -1
- package/dist/autoSense.js +24 -9
- package/dist/autoSense.js.map +1 -1
- package/dist/config.d.ts +9 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +15 -0
- package/dist/config.js.map +1 -1
- package/dist/diagnose.d.ts +1 -1
- package/dist/diagnose.js +1 -1
- package/dist/sensingRunMode.d.ts +8 -0
- package/dist/sensingRunMode.d.ts.map +1 -1
- package/dist/sensingRunMode.js +59 -11
- package/dist/sensingRunMode.js.map +1 -1
- package/package.json +5 -4
- package/retained/CapturedTheftProfile.cjs +83 -0
- package/retained/ExperimentalTheftConnector.cjs +392 -0
- package/retained/FrameTheftRuntime.cjs +111 -0
- package/retained/FrameTheftWorker.py +136 -0
- package/retained/InstalledTheftLifecycle.cjs +165 -0
- package/retained/InstalledTheftPackage.cjs +91 -0
- package/retained/LiveTheftBinding.cjs +55 -0
- package/retained/ObservedReviewCaseEvidence.py +188 -0
- package/retained/ObservedSameWristPolicy.py +205 -0
- package/retained/OrderedPerceptionDelivery.cjs +72 -0
- package/retained/PairedTheftRoute.cjs +402 -0
- package/retained/ReplayRpc.cjs +157 -0
- package/retained/RetainedCaptureClient.cjs +63 -16
- package/retained/SavedTheftSession.cjs +110 -0
- package/retained/TheftCaseContract.cjs +36 -0
- package/retained/TheftCaseDelivery.cjs +81 -0
- package/retained/TheftDeliveryPump.cjs +41 -0
- package/retained/TheftMovementOwner.py +234 -0
- package/retained/TheftReviewPolicy.cjs +8 -0
- package/retained/__tests__/paired-theft-manager.test.cjs +509 -0
- package/retained/__tests__/support/live-shelf-api.cjs +139 -0
- package/retained/__tests__/support/load-sdk-sources.cjs +41 -0
- package/retained/__tests__/support/loopback-proxy.cjs +33 -0
- package/retained/__tests__/support/pinned-api-loader.cjs +11 -0
- package/retained/__tests__/support/theft-builder.cjs +61 -0
- package/retained/__tests__/support/theft-packet-fixture.cjs +58 -0
- package/retained/__tests__/support/theft-readiness.cjs +51 -0
- package/retained/__tests__/test_live_theft_input.py +103 -0
- package/retained/__tests__/theft-case-api.test.cjs +135 -0
- package/retained/__tests__/theft-ci-regression.test.cjs +92 -0
- package/retained/__tests__/theft-config.test.cjs +84 -0
- package/retained/__tests__/theft-entry.test.cjs +76 -0
- package/retained/__tests__/theft-native-recovery.test.cjs +90 -0
- package/retained/__tests__/theft-readiness.test.cjs +164 -0
- package/retained/manager.cjs +61 -7
- package/retained/pilot-profile-client.cjs +4 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Exercise the actual catalogue, reviewed assignment, retained profile
|
|
4
|
+
// projection and case authority. Infrastructure, API schema wrappers and
|
|
5
|
+
// external providers are isolated from this SDK integration test.
|
|
6
|
+
const assert = require('node:assert/strict');
|
|
7
|
+
const fs = require('node:fs');
|
|
8
|
+
const path = require('node:path');
|
|
9
|
+
const Module = require('node:module');
|
|
10
|
+
const { createHash } = require('node:crypto');
|
|
11
|
+
const api = path.resolve(__dirname, '../../../../../../trillboard-api');
|
|
12
|
+
const real = relative => require(path.join(api, 'services', relative));
|
|
13
|
+
const binding = real('retainedTheftBindings.js');
|
|
14
|
+
const quickstarts = real('fein/cctvQuickstartProfiles.js');
|
|
15
|
+
const { retainedProfileTemplate } = quickstarts;
|
|
16
|
+
const { selectRetainedPilotModels } = real('retainedCctvModelSelection.js');
|
|
17
|
+
const frameRoutes = real('fein/alertFocusFields.js');
|
|
18
|
+
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
19
|
+
|
|
20
|
+
function load(relative, replacements, expose = '') {
|
|
21
|
+
const file = path.join(api, 'services', relative);
|
|
22
|
+
const loaded = new Module(file, module);
|
|
23
|
+
loaded.filename = file;
|
|
24
|
+
const fallback = Module.createRequire(file);
|
|
25
|
+
loaded.require = name => Object.hasOwn(replacements, name) ? replacements[name] : fallback(name);
|
|
26
|
+
loaded._compile(fs.readFileSync(file, 'utf8') + expose, file);
|
|
27
|
+
return loaded.exports;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function liveShelfFixture(feed, rf) {
|
|
31
|
+
const cameraId = feed.screenId;
|
|
32
|
+
const ownerId = 'pilot-owner';
|
|
33
|
+
const routeId = 'case-only-route';
|
|
34
|
+
const sourceId = hash({ url: new URL(feed.rtspUrl).toString(), crop: null });
|
|
35
|
+
const frameSize = [640, 480];
|
|
36
|
+
const shelf = [[100000, 100000], [800000, 100000], [800000, 600000]];
|
|
37
|
+
const regionConfigurationSha256 = hash([binding.LIVE_KIND, cameraId, sourceId, frameSize, shelf]);
|
|
38
|
+
const environment = { kind: binding.LIVE_KIND, cameraId, sourceId, frameSize, shelf, regionConfigurationSha256 };
|
|
39
|
+
const route = { routeId, ownerId, enabled: true, ownerKind: 'earner_user', mode: 'threshold',
|
|
40
|
+
condition: { field: binding.CASE_FIELD, op: 'eq', value: true }, screenMongoIds: [cameraId],
|
|
41
|
+
screenFocusRegions: [{ screenMongoId: cameraId, points: shelf.map(([x, y]) => ({ x: x / 1000000, y: y / 1000000 })) }] };
|
|
42
|
+
const row = { enabled: true, pilotMode: 'shelf', modeSinceMs: 1, templateId: binding.LIVE_TEMPLATE, reviewMode: 'human_only',
|
|
43
|
+
ownerId, routeId, sourceId, regionConfigurationSha256, frameSize };
|
|
44
|
+
const identity = { screenId: cameraId, ownerId };
|
|
45
|
+
const modelEligibility = { status: 'resolved', models: [rf] };
|
|
46
|
+
const runtimeConfig = { ensureLoaded: async () => {}, getJsonFailClosed: key => {
|
|
47
|
+
assert.equal(key, binding.KEY);
|
|
48
|
+
return { [cameraId]: row };
|
|
49
|
+
}, getBool: (_key, fallback) => fallback, getString: (_key, fallback) => fallback,
|
|
50
|
+
getInt: (_key, fallback) => fallback };
|
|
51
|
+
const routes = { async getRouteById(id, opts) {
|
|
52
|
+
assert.equal(id, routeId); assert.equal(opts.useReadReplica, false); return route;
|
|
53
|
+
} };
|
|
54
|
+
const readModelFixture = () => { throw Error('Test attempted to load a real provider or start a database'); };
|
|
55
|
+
const taxonomy = require(path.resolve(api, '../trillboards-iab-taxonomy/data/iab-taxonomy-1.1.json'));
|
|
56
|
+
const taxonomyPackage = { '@trillboards/iab-taxonomy/data/iab-taxonomy-1.1.json': taxonomy };
|
|
57
|
+
const hints = load('fein/iabHintTable.js', taxonomyPackage);
|
|
58
|
+
const ageVocabulary = load('audience/ageVocabulary.js', { ...taxonomyPackage, '../fein/iabHintTable': hints });
|
|
59
|
+
const speechVocabulary = load('fein/audienceTypedSignals.js', {
|
|
60
|
+
'../identity/BrandAffinityService': { loadBrandKgSeed: readModelFixture },
|
|
61
|
+
'../audience/ageVocabulary': ageVocabulary,
|
|
62
|
+
});
|
|
63
|
+
const program = load('fein/programSpec.js', { '../runtimeConfigService': runtimeConfig, './audienceTypedSignals': speechVocabulary });
|
|
64
|
+
const schema = { safeParse: value => ({ success: Boolean(value && typeof value === 'object') }) };
|
|
65
|
+
const profiles = load('fein/sensingProfileService.js', {
|
|
66
|
+
uuid: { v4: () => '01111111-2222-3333-4444-555555555555' },
|
|
67
|
+
'../sensing/senseRequestContext': {}, '../postgresClient': { query: readModelFixture },
|
|
68
|
+
'../runtimeConfigService': runtimeConfig, '../deviceCommandDispatcher': {}, '../pgRepo/screens': {},
|
|
69
|
+
'./sensingModelRegistry': { getActiveModels: async () => ({}) }, './programSpec': program, './audienceTypedSignals': speechVocabulary,
|
|
70
|
+
'./sensingIntentService': { MetricsSchemaEntrySchema: schema, SignalDeclarationSchema: schema, SensingConfigSchema: schema },
|
|
71
|
+
});
|
|
72
|
+
const deps = { runtimeConfig, routes, modelEligibility: async () => modelEligibility };
|
|
73
|
+
const bound = { ...binding, resolveLiveTarget: input => binding.resolveLiveTarget(input, deps) };
|
|
74
|
+
const deployment = load('fein/sensingProfileChangeService.js', {
|
|
75
|
+
'../sensing/senseRequestContext': {}, '../postgresClient': { query: readModelFixture },
|
|
76
|
+
'../pgRepo/sensingRoutes': {}, '../retainedTheftBindings': bound,
|
|
77
|
+
'./sensingProfileService': { ...profiles, resolveDeviceIdentityForScreen: async ({ screenId }) => ({
|
|
78
|
+
fingerprint: 'fixture-device', deviceId: screenId,
|
|
79
|
+
}) },
|
|
80
|
+
}, '\nmodule.exports.localFixture = { deploymentSelector, deploymentSource, deploymentReceiptId, prepareDeploymentTarget };').localFixture;
|
|
81
|
+
const retained = load('retainedCctvPilotProfile.js', {
|
|
82
|
+
'./retainedCctvReviewService': { authorizeRetainedCamera: async () => ({ identity, repository: {} }) },
|
|
83
|
+
'./sensing/boxMethodEngagement': { advertisedMethods: () => new Set() }, './sensing/sceneMarks': {},
|
|
84
|
+
});
|
|
85
|
+
let saved = null;
|
|
86
|
+
const inactive = { success: true, screenId: cameraId, profileState: 'inactive', profileId: null, profileName: null,
|
|
87
|
+
profileType: null, fields: [], fieldRouting: { vlm: [], producer: [], withheld: [], alertFocusRegions: [] },
|
|
88
|
+
absenceWatchedFields: [], models: [], classes: [] };
|
|
89
|
+
|
|
90
|
+
async function serve(headers = {}, internal = false) {
|
|
91
|
+
if (!saved) return selectRetainedPilotModels(inactive, cameraId);
|
|
92
|
+
let body;
|
|
93
|
+
const response = { status(code) { assert.equal(code, 200); return this; },
|
|
94
|
+
json(value) { body = value; return this; }, set() { return this; } };
|
|
95
|
+
await retained.profile({ headers }, response, { ...deps, allowLiveCaseProfile: internal, profile: async () =>
|
|
96
|
+
binding.liveProfileInput(saved, inactive, retainedProfileTemplate(saved)) });
|
|
97
|
+
return body;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return { identity, row, route, environment, modelEligibility, registration: {
|
|
101
|
+
feedName: feed.name, reviewMode: 'human_only', sceneId: 1, templateId: binding.LIVE_TEMPLATE, environment,
|
|
102
|
+
}, serve,
|
|
103
|
+
verifyCatalogueIsolation() {
|
|
104
|
+
assert.equal(quickstarts.alertTemplateProfile(binding.LIVE_TEMPLATE), null);
|
|
105
|
+
assert.equal(quickstarts.alertQuestionForTemplate(binding.LIVE_TEMPLATE), null);
|
|
106
|
+
assert.equal(quickstarts.alertQuestionForTemplate(quickstarts.CONCEALMENT_TEMPLATE, { colour: 'red' }).field, 'concealment_suspected');
|
|
107
|
+
assert.equal(quickstarts.alertQuestionForTemplate(quickstarts.FLOOR_TEMPLATE).field, 'floor_object_left');
|
|
108
|
+
const before = profiles.listBuiltinProfiles().map(profile => profile.profile_id);
|
|
109
|
+
assert.equal(before.includes(binding.LIVE_TEMPLATE), false);
|
|
110
|
+
assert.deepEqual(profiles.listBuiltinProfiles({ includeShelfMovementReview: true }).map(profile => profile.profile_id),
|
|
111
|
+
[...before, binding.LIVE_TEMPLATE]);
|
|
112
|
+
assert.throws(() => profiles.getBuiltinProfileForDeployment(binding.LIVE_TEMPLATE, { colour: 'red' }),
|
|
113
|
+
{ code: 'profile_template_parameters_invalid' });
|
|
114
|
+
},
|
|
115
|
+
ordinaryRouteFields() {
|
|
116
|
+
return [frameRoutes.alertQuestionEntry(route), frameRoutes.observedFieldForRoute(route, cameraId),
|
|
117
|
+
frameRoutes.buildAlertFocusMetrics([route], cameraId), frameRoutes.buildAlertFocusRegions([route], cameraId)];
|
|
118
|
+
},
|
|
119
|
+
async select(reviewRevision) {
|
|
120
|
+
const input = { templateId: binding.LIVE_TEMPLATE, userId: ownerId, actorId: 'operator', screenId: cameraId,
|
|
121
|
+
action: 'add', reviewRevision };
|
|
122
|
+
const source = await deployment.deploymentSource(input);
|
|
123
|
+
const receipt = deployment.deploymentReceiptId(input, source.selector);
|
|
124
|
+
const target = await deployment.prepareDeploymentTarget(input, source, cameraId, 'add', receipt);
|
|
125
|
+
assert.equal(target.prepared.profile.sensing_config.speech.useLlmExtractor, false);
|
|
126
|
+
saved = target.prepared.profile;
|
|
127
|
+
return receipt;
|
|
128
|
+
},
|
|
129
|
+
stop() { saved = null; },
|
|
130
|
+
setPilotMode(pilotMode, modeSinceMs) { Object.assign(row, { pilotMode, modeSinceMs }); },
|
|
131
|
+
allowsConcealment(capturedAtMs) { return binding.permitsConcealmentReview(identity, capturedAtMs, deps); },
|
|
132
|
+
async resolveCase() {
|
|
133
|
+
return binding.resolve(identity, {}, { ...deps, readTheftProfile: () => serve({}, true) });
|
|
134
|
+
},
|
|
135
|
+
async canOffer(user) { return binding.canOfferLiveTemplate(user, deps); },
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
module.exports = { liveShelfFixture };
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Test preload only. Compile the real SDK/core dependency graph in the shipped
|
|
3
|
+
// CommonJS mode, using the already-installed TypeScript package. No stubs,
|
|
4
|
+
// emitted build tree, installation, native worker or camera/model start.
|
|
5
|
+
const fs = require('node:fs'), path = require('node:path'), Module = require('node:module');
|
|
6
|
+
const ts = require('typescript');
|
|
7
|
+
const sdk = path.resolve(__dirname, '../../..');
|
|
8
|
+
const core = path.resolve(sdk, '../edge-core');
|
|
9
|
+
const resolve = Module._resolveFilename, loader = require.extensions['.ts'];
|
|
10
|
+
const within = (root, file) => file.startsWith(root + path.sep);
|
|
11
|
+
Module._resolveFilename = function(request, parent, ...rest) {
|
|
12
|
+
if (request === '@trillboards/edge-core') return path.join(core, 'src/index.ts');
|
|
13
|
+
if ((request.startsWith('.') || path.isAbsolute(request)) && parent?.filename && within(sdk, parent.filename)) {
|
|
14
|
+
const filename = path.resolve(path.dirname(parent.filename), request);
|
|
15
|
+
if (within(path.join(sdk, 'dist'), filename)) {
|
|
16
|
+
const source = path.join(sdk, 'src', path.relative(path.join(sdk, 'dist'), filename)).replace(/\.js$/, '') + '.ts';
|
|
17
|
+
if (fs.existsSync(source)) return source;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return resolve.call(this, request, parent, ...rest);
|
|
21
|
+
};
|
|
22
|
+
require.extensions['.ts'] = function(module, filename) {
|
|
23
|
+
if (!within(path.join(sdk, 'src'), filename) && !within(path.join(core, 'src'), filename)) {
|
|
24
|
+
if (loader) return loader(module, filename);
|
|
25
|
+
throw Error('Unexpected TypeScript source outside the two selected packages');
|
|
26
|
+
}
|
|
27
|
+
const compiled = ts.transpileModule(fs.readFileSync(filename, 'utf8'), {
|
|
28
|
+
compilerOptions: {module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, esModuleInterop: true},
|
|
29
|
+
fileName: filename, reportDiagnostics: true,
|
|
30
|
+
});
|
|
31
|
+
const errors = compiled.diagnostics?.filter(item => item.category === ts.DiagnosticCategory.Error) ?? [];
|
|
32
|
+
if (errors.length) throw Error(ts.formatDiagnosticsWithColorAndContext(errors, {
|
|
33
|
+
getCurrentDirectory: () => sdk, getCanonicalFileName: file => file, getNewLine: () => '\n',
|
|
34
|
+
}));
|
|
35
|
+
module._compile(compiled.outputText, filename);
|
|
36
|
+
};
|
|
37
|
+
process.once('exit', () => {
|
|
38
|
+
Module._resolveFilename = resolve;
|
|
39
|
+
if (loader) require.extensions['.ts'] = loader;
|
|
40
|
+
else delete require.extensions['.ts'];
|
|
41
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Test-process-only simulated OS discovery. This never executes an OS helper.
|
|
3
|
+
const fs=require('node:fs'),path=require('node:path'),assert=require('node:assert/strict');
|
|
4
|
+
const owned=process.env.THEFT_PROXY_AUDIT?null:fs.mkdtempSync(path.join(require('node:os').tmpdir(),'theft-proxy-'));
|
|
5
|
+
const output=process.env.THEFT_PROXY_AUDIT||path.join(owned,'audit');assert(path.isAbsolute(output));
|
|
6
|
+
const fd=fs.openSync(output+'.'+process.pid+'.jsonl','wx',0o600),calls=[];
|
|
7
|
+
const record=value=>fs.writeSync(fd,JSON.stringify({pid:process.pid,atMs:Date.now(),...value})+'\n');
|
|
8
|
+
record({event:'fixture_start',scope:'simulated Windows proxy reader; no real proxy qualification'});
|
|
9
|
+
const KEY='HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings';
|
|
10
|
+
function fixtureExec(command,args){
|
|
11
|
+
let stdout;
|
|
12
|
+
if(command==='reg.exe'&&JSON.stringify(args)===JSON.stringify(['query',KEY]))stdout=KEY+'\r\n ProxyEnable REG_DWORD 0x0\r\n';
|
|
13
|
+
else if(command==='netsh.exe'&&JSON.stringify(args)===JSON.stringify(['winhttp','show','proxy']))stdout='Current WinHTTP proxy settings:\r\n Direct access (no proxy server).\r\n';
|
|
14
|
+
else throw Error('Undeclared simulated proxy-reader command');
|
|
15
|
+
calls.push({command,args});record({event:'simulated_proxy_read',command,args});
|
|
16
|
+
return {pid:0,output:[null,stdout,''],stdout,stderr:'',status:0,signal:null};
|
|
17
|
+
}
|
|
18
|
+
function rawError(error){return Object.fromEntries(['name','message','code','errno','syscall','address','port','stack'].filter(k=>error?.[k]!==undefined).map(k=>[k,error[k]]));}
|
|
19
|
+
const proxy=require('../../../src/enterpriseProxy.ts'),originalResolve=proxy.resolveProxyForUrl;
|
|
20
|
+
proxy.resolveProxyForUrl=function(url,options={}){
|
|
21
|
+
let parsed;try{parsed=new URL(url);}catch{return originalResolve(url,options);}
|
|
22
|
+
if(parsed.protocol!=='http:'||!['127.0.0.1','localhost','[::1]'].includes(parsed.hostname)||options.exec||options.platform||options.env)return originalResolve(url,options);
|
|
23
|
+
try{return originalResolve(url,{...options,platform:'win32',env:{},exec:fixtureExec});}
|
|
24
|
+
catch(error){record({event:'resolver_rejection',origin:parsed.origin,error:rawError(error)});throw error;}
|
|
25
|
+
};
|
|
26
|
+
const sdk=require('../../../src/AudienceAnalyzeClient.ts'),originalPoster=sdk.defaultHttpPoster;
|
|
27
|
+
sdk.defaultHttpPoster=function(...args){
|
|
28
|
+
let origin;try{origin=new URL(args[0]).origin;}catch{origin='invalid';}
|
|
29
|
+
try{return originalPoster.apply(this,args).catch(error=>{record({event:'poster_rejection',origin,error:rawError(error)});throw error;});}
|
|
30
|
+
catch(error){record({event:'poster_rejection',origin,error:rawError(error)});throw error;}
|
|
31
|
+
};
|
|
32
|
+
process.on('exit',code=>{record({event:'fixture_exit',code,simulatedReads:calls.length});fs.closeSync(fd);if(owned){fs.unlinkSync(output+'.'+process.pid+'.jsonl');fs.rmdirSync(owned);}});
|
|
33
|
+
module.exports={fixtureExec,originalResolve,calls,KEY};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs=require('node:fs'),path=require('node:path'),Module=require('node:module');
|
|
3
|
+
const root=path.resolve(__dirname,'../../../../../..');
|
|
4
|
+
const api=path.join(root,'trillboard-api'),contracts=api;
|
|
5
|
+
function load(file,stubs={}){
|
|
6
|
+
const m=new Module(file,module);m.filename=file;m.paths=Module._nodeModulePaths(path.dirname(file));
|
|
7
|
+
m.require=name=>Object.hasOwn(stubs,name)?stubs[name]:name.startsWith('node:')||Module.builtinModules.includes(name)?require(name):(()=>{throw Error('Unstubbed external dependency: '+name+' from '+file);})();
|
|
8
|
+
m._compile(fs.readFileSync(file,'utf8'),file);return m.exports;
|
|
9
|
+
}
|
|
10
|
+
const logger={info(){},warn(){},error(){},child(){return this;}};
|
|
11
|
+
module.exports={root,api,contracts,load,logger};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),vm=require('node:vm');
|
|
3
|
+
const {EventEmitter}=require('node:events');
|
|
4
|
+
const {InstalledTheftLifecycle}=require('../../InstalledTheftLifecycle.cjs');
|
|
5
|
+
const root=path.resolve(__dirname,'../../..');
|
|
6
|
+
const ts=require('typescript');
|
|
7
|
+
// Test-only transpilation; no semantic release build or native qualification.
|
|
8
|
+
const sourceFile=path.join(root,'src/sensingRunMode.ts');
|
|
9
|
+
const output=ts.transpileModule(fs.readFileSync(sourceFile,'utf8'),{fileName:sourceFile,
|
|
10
|
+
compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS},reportDiagnostics:true});
|
|
11
|
+
assert.equal((output.diagnostics??[]).filter(d=>d.category===ts.DiagnosticCategory.Error).length,0);
|
|
12
|
+
function fixture(options={}) {
|
|
13
|
+
const factoryCalls=[],imports=[],events=[],owners=[],diagnostics=[];
|
|
14
|
+
const manager=new EventEmitter();
|
|
15
|
+
manager.start=async function(options){assert.equal(this,manager);events.push(['start',options]);};
|
|
16
|
+
manager.stop=async function(){assert.equal(this,manager);events.push(['stop']);};
|
|
17
|
+
manager.getSensingHealth=()=>({localInferences:0});
|
|
18
|
+
const originalStart=manager.start,originalStop=manager.stop;
|
|
19
|
+
const lifecycle=new InstalledTheftLifecycle({
|
|
20
|
+
makeFrame:settings=>{owners.push(settings);return {reviewer:null,rpc:{call:async(method,body)=>({method,body})},
|
|
21
|
+
async start(){},async close(){return {exited:true};}};},
|
|
22
|
+
describeOriginal:value=>value,availableBytes:()=>5000000000,onDiagnostic:row=>diagnostics.push(row),
|
|
23
|
+
});
|
|
24
|
+
Object.defineProperty(lifecycle.runtime,'installedLifecycle',{value:lifecycle,enumerable:false});
|
|
25
|
+
const unused=new Set(['./localSensing','./AudienceAnalyzeClient','./SenseTelemetryReporter','./SensingProfileClient',
|
|
26
|
+
'./deployedCadenceSource','./DetectorShadowProbe','./transportFailure']);
|
|
27
|
+
const exports={},module={exports};
|
|
28
|
+
const requireBoundary=request=>{
|
|
29
|
+
imports.push(request);
|
|
30
|
+
if(['path','crypto'].includes(request))return require(request);
|
|
31
|
+
if(request==='./CloudSensingManager')return {resolveFeeds:config=>config.cameras??[]};
|
|
32
|
+
if(request==='./continuousReview')return {retainedReviewApiBase:(_review,base)=>base};
|
|
33
|
+
if(request==='./dataDir')return {resolveDataDir:value=>value};
|
|
34
|
+
if(request==='./RecorderAddressRecovery')return {RecorderAddressRecovery:class {async recover(){return null;}}};
|
|
35
|
+
if(request==='../retained/manager.cjs')return {createWebsiteManager:async(...args)=>{
|
|
36
|
+
factoryCalls.push(args);if(options.factoryError)throw options.factoryError;return {manager};
|
|
37
|
+
}};
|
|
38
|
+
if(request==='../retained/InstalledTheftLifecycle.cjs')return {InstalledTheftLifecycle};
|
|
39
|
+
if(request==='../retained/InstalledTheftPackage.cjs')return {loadInstalledTheftPackage:settings=>{
|
|
40
|
+
assert.equal(typeof options.installedLoad,'function','Explicit package-loader boundary required');
|
|
41
|
+
return options.installedLoad(settings);
|
|
42
|
+
}};
|
|
43
|
+
if(unused.has(request))return {};
|
|
44
|
+
throw Error('Unplanned builder dependency: '+request);
|
|
45
|
+
};
|
|
46
|
+
const intervalHandles=[];
|
|
47
|
+
const isolatedProcess=options.environment===undefined?process:Object.create(process);
|
|
48
|
+
if(options.environment!==undefined)Object.defineProperty(isolatedProcess,'env',{value:{NODE_ENV:'test',...options.environment}});
|
|
49
|
+
new vm.Script(output.outputText,{filename:sourceFile}).runInNewContext({require:requireBoundary,module,exports,
|
|
50
|
+
process:isolatedProcess,Buffer,URL,console,setTimeout,clearTimeout,setInterval:()=>{
|
|
51
|
+
const handle={unref(){this.unreferenced=true;}};intervalHandles.push(handle);return handle;
|
|
52
|
+
},clearInterval:()=>{} });
|
|
53
|
+
const config={apiBaseUrl:'https://example.invalid',deviceToken:'test-fixture-only',dataDir:path.join(root,'unused-data'),
|
|
54
|
+
cameras:[{name:'fixture-camera',screenId:'fixture-screen',deviceToken:'test-fixture-only'}],
|
|
55
|
+
localSensing:{model:'gemma-4-E2B-it.litertlm'},cloudSensing:{candidateBuffer:{continuousReview:{enabled:true,deliveryTarget:'configured-api'}}}};
|
|
56
|
+
const registration={version:1,profiles:[{feedName:'fixture-camera',profileId:'theft',selectionId:'fixture-selection',sceneId:0,
|
|
57
|
+
reviewMode:'human_only',environment:{sourceVideoSha256:'a'.repeat(64),regionConfigurationSha256:'b'.repeat(64),frameSize:[640,480]}}]};
|
|
58
|
+
return {api:module.exports,config,registration,io:{log(){},warn(){},error(){}},lifecycle,manager,originalStart,originalStop,
|
|
59
|
+
factoryCalls,imports,events,owners,diagnostics,intervalHandles};
|
|
60
|
+
}
|
|
61
|
+
module.exports={fixture};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
const assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');
|
|
3
|
+
const {actorProofHash}=require('../../../dist/ActorTracking');
|
|
4
|
+
const {ExperimentalTheftConnector,PrivateAlertReceiver,RF,POSE}=require('../../ExperimentalTheftConnector.cjs');
|
|
5
|
+
const {OBSERVED_TIMING}=require('../../FrameTheftRuntime.cjs');
|
|
6
|
+
const sha=b=>crypto.createHash('sha256').update(b).digest('hex');
|
|
7
|
+
const dirs=[],connectors=[];
|
|
8
|
+
function packetFixture({positive = true, reviewer = null,captureStep=500,observedTiming=false} = {}) {
|
|
9
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'private237-')); dirs.push(directory);
|
|
10
|
+
const environment = {sourceVideoSha256: 'a'.repeat(64), regionConfigurationSha256: 'b'.repeat(64), frameSize: [640,480]};
|
|
11
|
+
const scope = {cameraId: 'camera', sourceId: 'source', captureEpoch: 'epoch', profileGeneration: 1,
|
|
12
|
+
sceneId: 1, sourceVideoSha256: environment.sourceVideoSha256, regionConfigurationSha256: environment.regionConfigurationSha256};
|
|
13
|
+
const actor = {kind: 'person', cameraId: 'camera', epoch: 'e', id: 'p'};
|
|
14
|
+
const actorHash = actorProofHash(actor); const originals = []; let calls = 0, now = 106100;
|
|
15
|
+
const rpc = {async call(method, body) {
|
|
16
|
+
assert.equal(method, 'detect'); calls++;
|
|
17
|
+
const f = body.native_frame; originals.push(f);
|
|
18
|
+
const unsigned = {...body.tracking, algorithm: 'bytetrack_2.6.1', epoch: 'e', imageSha256: f.sha256,
|
|
19
|
+
contextSha256: 'c'.repeat(64), modelHashes: {rfdetr_medium: RF}, continuity: 'continued',
|
|
20
|
+
actors: [{detectionIndex: 0, actor}], unconfirmed: [], endedActors: []};
|
|
21
|
+
const tracking = {...unsigned, sha256: actorProofHash(unsigned)};
|
|
22
|
+
const reference = x => [x.sourceIndex, x.capturedAtMs, x.sha256];
|
|
23
|
+
const receipts = positive && originals.length === 13 ? [{caseId: 'd'.repeat(64), actor: actorHash,
|
|
24
|
+
kind: 'open_case', firstCaptureMs:originals[6].capturedAtMs, deadlineMs:originals[6].capturedAtMs+90000, snapshotAnchorMs: f.capturedAtMs,
|
|
25
|
+
...(observedTiming?{captureTimingPolicy:OBSERVED_TIMING}:{}),
|
|
26
|
+
pictures: originals.map(reference), episodes: [{originMs:originals[4].capturedAtMs, arrivalMs:originals[6].capturedAtMs,
|
|
27
|
+
side: 'right', support: originals.slice(4,7).map(reference)}]}] : [];
|
|
28
|
+
return {detections: [{label: 'person', confidence: .9, box: {x: 100, y: 70, width: 180, height: 300}}],
|
|
29
|
+
inference_ms: 3, model: 'rfdetr_medium', model_hashes: {rfdetr_medium: RF}, tracking,
|
|
30
|
+
lab_sidecar: {...(observedTiming?{captureTimingPolicy:OBSERVED_TIMING}:{}),inputBinding: {...body.tracking, testOnly: false, nativeScope: scope,
|
|
31
|
+
imageSha256: f.sha256, poseModelSha256: POSE, modelHashes: {rfdetr_medium: RF}, trackingSha256: tracking.sha256},
|
|
32
|
+
cameraEvidence: {guard: 'stable_hypothesis', trackerResetDiagnostic: false, resetMovementEvidence: false},
|
|
33
|
+
movementObservation: {cues: [], caseEvidenceReceipts: receipts}}};
|
|
34
|
+
}};
|
|
35
|
+
const receiver = new PrivateAlertReceiver(path.join(directory, 'alerts'));
|
|
36
|
+
const connector = new ExperimentalTheftConnector({directory, scope, environment, rpc, receiver, reviewer, now: () => now});
|
|
37
|
+
async function captureFrame(i) {
|
|
38
|
+
const jpeg = Buffer.concat([Buffer.from([255,216,255,192,0,11,8,1,224,2,128,1,1,17,0,255,217]), Buffer.from(String(i))]);
|
|
39
|
+
await connector.capture({sourceIndex: i * 15, sourceTimeMs: null, sceneId: 1, width: 640, height: 480,
|
|
40
|
+
capturedAtMs: 100000 + i * captureStep, sha256: sha(jpeg), jpegBase64: jpeg.toString('base64')});
|
|
41
|
+
}
|
|
42
|
+
async function capture(){for(let i=0;i<13;i++)await captureFrame(i);}
|
|
43
|
+
return {connector, receiver, scope, directory, capture, captureFrame, calls: () => calls, setNow: v => now = v};
|
|
44
|
+
}
|
|
45
|
+
function fixture(options){const f=packetFixture(options);connectors.push(f.connector);return f;}
|
|
46
|
+
function cleanupFixtures(){
|
|
47
|
+
const errors=[];
|
|
48
|
+
for(const c of connectors.splice(0)){try{c.close();}catch(e){errors.push(e);}}
|
|
49
|
+
for(const d of dirs.splice(0)){try{
|
|
50
|
+
assert.equal(path.dirname(path.resolve(d)),path.resolve(os.tmpdir()));
|
|
51
|
+
assert(path.basename(d).startsWith('private237-'));
|
|
52
|
+
const owned=fs.realpathSync(d),base=fs.realpathSync(os.tmpdir());
|
|
53
|
+
assert(owned.startsWith(base+path.sep)&&!fs.lstatSync(d).isSymbolicLink());
|
|
54
|
+
fs.rmSync(owned,{recursive:true});assert(!fs.existsSync(d));
|
|
55
|
+
}catch(e){errors.push(e);}}
|
|
56
|
+
if(errors.length)throw new AggregateError(errors,'Packet fixture cleanup failed');
|
|
57
|
+
}
|
|
58
|
+
module.exports={fixture,cleanupFixtures};
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const assert=require('node:assert/strict'),fs=require('node:fs'),path=require('node:path'),vm=require('node:vm');
|
|
3
|
+
const root=path.resolve(__dirname,'../../..');
|
|
4
|
+
const ts=require('typescript');
|
|
5
|
+
// Source-boundary regression checks, not native/runtime qualification.
|
|
6
|
+
class Spool {expire(){this.expired=(this.expired??0)+1;}}
|
|
7
|
+
class NativeError extends Error {constructor(message,kind='unavailable'){super(message);this.kind=kind;}}
|
|
8
|
+
class WebsiteBase {
|
|
9
|
+
isReviewActive(){return this.reviewActive!==false;}
|
|
10
|
+
captureReviewContext(){if(this.contextError)throw this.contextError;return this.context;}
|
|
11
|
+
hasPendingOrderedPerception(){return !this.busy&&!!this.pending;}
|
|
12
|
+
pendingPerception(){return this.pending;}
|
|
13
|
+
}
|
|
14
|
+
function load(relative,extra={}) {
|
|
15
|
+
const file=path.join(root,relative),source=fs.readFileSync(file,'utf8');
|
|
16
|
+
const compiled=relative.endsWith('.ts')?ts.transpileModule(source,{fileName:file,reportDiagnostics:true,
|
|
17
|
+
compilerOptions:{target:ts.ScriptTarget.ES2022,module:ts.ModuleKind.CommonJS}}):{outputText:source,diagnostics:[]};
|
|
18
|
+
assert.equal((compiled.diagnostics??[]).filter(d=>d.category===ts.DiagnosticCategory.Error).length,0);
|
|
19
|
+
const imports=[],exports={},module={exports};
|
|
20
|
+
const special={
|
|
21
|
+
'./LiteRtVlmProvider':{GPU_MODEL_SUFFIX:',gpu'},
|
|
22
|
+
'./DurableVlmCandidateSpool':{DurableVlmCandidateSpool:Spool},
|
|
23
|
+
'./NativeReadiness':{NativeReadinessError:NativeError},
|
|
24
|
+
'../dist/NativeReadiness':{isNativeReadinessUnavailable:error=>error instanceof NativeError&&error.kind==='unavailable'},
|
|
25
|
+
'./WebsiteAdmissionCaptureClient.cjs':{WebsiteAdmissionCaptureClient:WebsiteBase},
|
|
26
|
+
'./TheftReviewPolicy.cjs':require('../../TheftReviewPolicy.cjs'),
|
|
27
|
+
...extra,
|
|
28
|
+
};
|
|
29
|
+
const localRequire=request=>{
|
|
30
|
+
imports.push(request);
|
|
31
|
+
if(request.startsWith('node:')||['events','fs','http','https','url','crypto','path'].includes(request))return require(request);
|
|
32
|
+
if(Object.hasOwn(special,request))return special[request];
|
|
33
|
+
// Unused import boundaries remain unavailable. Executing one fails, never
|
|
34
|
+
// silently falls back to a model, camera, network or production module.
|
|
35
|
+
return {};
|
|
36
|
+
};
|
|
37
|
+
new vm.Script(compiled.outputText,{filename:file}).runInNewContext({require:localRequire,module,exports,
|
|
38
|
+
process,Buffer,URL,console,setTimeout,clearTimeout,setInterval,clearInterval,performance,structuredClone});
|
|
39
|
+
return {...module.exports,imports};
|
|
40
|
+
}
|
|
41
|
+
function supervisorFixture(manager,health={ok:false,reason:'Gemma unavailable'}) {
|
|
42
|
+
const {AutoSenseSupervisor}=load('src/autoSense.ts'),logs=[],timers=new Set();let probes=0;
|
|
43
|
+
const deps={probe:async()=>{probes++;return typeof health==='function'?health():health;},
|
|
44
|
+
buildLocalManager:async()=>manager,log:value=>logs.push(value),sleep:async()=>{},
|
|
45
|
+
setTimer:callback=>{const timer={callback};timers.add(timer);return timer;},clearTimer:timer=>timers.delete(timer),
|
|
46
|
+
onNoFeeds:()=>{throw Error('Unexpected no-feeds fixture');},startupAttempts:1,startupBackoffMs:0,
|
|
47
|
+
recheckIntervalMs:1000,unhealthyChecksBeforeFallback:2,litertLmBaseUrl:'http://127.0.0.1:1',
|
|
48
|
+
expectedModel:'gemma-4-E2B-it.litertlm',probeTimeoutMs:1};
|
|
49
|
+
return {supervisor:new AutoSenseSupervisor(deps),logs,timers,get probes(){return probes;}};
|
|
50
|
+
}
|
|
51
|
+
module.exports={load,supervisorFixture,Spool,NativeError,WebsiteBase};
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Model-free checks of the live worker protocol and hash-pinned replay path."""
|
|
2
|
+
|
|
3
|
+
import copy
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import sys
|
|
8
|
+
import tempfile
|
|
9
|
+
import unittest
|
|
10
|
+
|
|
11
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
12
|
+
from FrameTheftWorker import read_configuration
|
|
13
|
+
from TheftMovementOwner import LIVE_KIND, OBSERVED_TIMING, LiveMovementAdapter, prepare_live_cameras
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class OwnerFixture:
|
|
17
|
+
def __init__(self):
|
|
18
|
+
self.requests = []
|
|
19
|
+
|
|
20
|
+
def detect_wire(self, request):
|
|
21
|
+
self.requests.append(copy.deepcopy(request))
|
|
22
|
+
scope = request['native_scope']
|
|
23
|
+
return {'lab_sidecar': {'inputBinding': {'nativeScope': scope, 'imageSha256': 'b' * 64},
|
|
24
|
+
'movementObservation': {'cues': [{'scope': scope, 'side': 'right'}]}}}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class LiveInputTest(unittest.TestCase):
|
|
28
|
+
def setUp(self):
|
|
29
|
+
camera, source = 'camera-one', 'a' * 64
|
|
30
|
+
size = [640, 480]
|
|
31
|
+
shelf = [[100000, 100000], [800000, 100000], [800000, 600000]]
|
|
32
|
+
region = hashlib.sha256(json.dumps(
|
|
33
|
+
[LIVE_KIND, camera, source, size, shelf], separators=(',', ':')).encode()).hexdigest()
|
|
34
|
+
self.environment = {'kind': LIVE_KIND, 'cameraId': camera, 'sourceId': source,
|
|
35
|
+
'frameSize': size, 'shelf': shelf, 'regionConfigurationSha256': region}
|
|
36
|
+
self.config = {'cameraEnvironments': {camera: self.environment}}
|
|
37
|
+
self.scope = {'cameraId': camera, 'sourceId': source, 'sourceKind': LIVE_KIND,
|
|
38
|
+
'captureEpoch': 'capture-one', 'profileGeneration': 1, 'sceneId': 2,
|
|
39
|
+
'regionConfigurationSha256': region}
|
|
40
|
+
self.request = {'tracking': {'cameraId': camera, 'sourceId': source}, 'native_scope': self.scope}
|
|
41
|
+
|
|
42
|
+
def test_live_round_trip_uses_original_geometry_and_does_not_emit_replay_provenance(self):
|
|
43
|
+
normalized, bindings = prepare_live_cameras(self.config)
|
|
44
|
+
legacy = normalized['cameraEnvironments']['camera-one']['environment']
|
|
45
|
+
self.assertEqual(legacy['regions'][0]['region']['points'],
|
|
46
|
+
[{'x': .1, 'y': .1}, {'x': .8, 'y': .1}, {'x': .8, 'y': .6}])
|
|
47
|
+
self.assertNotIn('sourceVideoSha256', self.environment)
|
|
48
|
+
owner = OwnerFixture()
|
|
49
|
+
adapted = LiveMovementAdapter(owner, bindings)
|
|
50
|
+
wire = adapted.detect_wire(self.request)
|
|
51
|
+
self.assertEqual(owner.requests[0]['native_scope']['sourceVideoSha256'], legacy['sourceVideoSha256'])
|
|
52
|
+
self.assertNotEqual(owner.requests[0]['native_scope']['sourceVideoSha256'], self.scope['sourceId'])
|
|
53
|
+
self.assertEqual(wire['lab_sidecar']['inputBinding']['nativeScope'], self.scope)
|
|
54
|
+
self.assertEqual(wire['lab_sidecar']['movementObservation']['cues'][0]['scope'], self.scope)
|
|
55
|
+
self.assertNotIn('sourceVideoSha256', json.dumps(wire))
|
|
56
|
+
with self.assertRaisesRegex(ValueError, 'does not expose optional'):
|
|
57
|
+
adapted.movement_packet({})
|
|
58
|
+
|
|
59
|
+
def test_changed_source_or_shelf_cannot_start_the_worker(self):
|
|
60
|
+
_, bindings = prepare_live_cameras(self.config)
|
|
61
|
+
owner = OwnerFixture()
|
|
62
|
+
adapted = LiveMovementAdapter(owner, bindings)
|
|
63
|
+
for field, value in [('regionConfigurationSha256', 'c' * 64), ('sourceId', 'd' * 64)]:
|
|
64
|
+
wrong = copy.deepcopy(self.request)
|
|
65
|
+
wrong['native_scope'][field] = value
|
|
66
|
+
with self.assertRaisesRegex(ValueError, 'scope differs'):
|
|
67
|
+
adapted.detect_wire(wrong)
|
|
68
|
+
self.assertEqual(owner.requests, [])
|
|
69
|
+
changed = copy.deepcopy(self.config)
|
|
70
|
+
changed['cameraEnvironments']['camera-one']['shelf'][0][0] += 1
|
|
71
|
+
with self.assertRaisesRegex(ValueError, 'fingerprint differs'):
|
|
72
|
+
prepare_live_cameras(changed)
|
|
73
|
+
|
|
74
|
+
def test_recorded_camera_is_delegated_without_rewriting_its_original_scope(self):
|
|
75
|
+
_, bindings = prepare_live_cameras(self.config)
|
|
76
|
+
owner = OwnerFixture()
|
|
77
|
+
replay = {'tracking': {'cameraId': 'replay'}, 'native_scope': {'sourceVideoSha256': '3' * 64,
|
|
78
|
+
'regionConfigurationSha256': '4' * 64}}
|
|
79
|
+
wire = LiveMovementAdapter(owner, bindings).detect_wire(replay)
|
|
80
|
+
self.assertEqual(owner.requests, [replay])
|
|
81
|
+
self.assertEqual(wire['lab_sidecar']['inputBinding']['nativeScope'], replay['native_scope'])
|
|
82
|
+
|
|
83
|
+
def test_versioned_frame_configuration_keeps_the_replay_contract(self):
|
|
84
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
85
|
+
file = Path(directory) / 'config.json'
|
|
86
|
+
native = {'labRoot': directory, 'journalPath': directory, 'frameRate': 2,
|
|
87
|
+
'maxCameras': 1, 'rfdetrThreads': 4, 'poseThreads': 2}
|
|
88
|
+
sources = {key: {} for key in ('native', 'case', 'wrist')}
|
|
89
|
+
def read(version, environments):
|
|
90
|
+
config = {'version': version, 'nativeConfig': {**native, 'cameraEnvironments': environments},
|
|
91
|
+
'sources': sources, 'captureTimingPolicy': OBSERVED_TIMING}
|
|
92
|
+
raw = json.dumps(config).encode()
|
|
93
|
+
file.write_bytes(raw)
|
|
94
|
+
return read_configuration(file, hashlib.sha256(raw).hexdigest())
|
|
95
|
+
self.assertEqual(read(3, self.config['cameraEnvironments'])['captureTimingPolicy'], OBSERVED_TIMING)
|
|
96
|
+
with self.assertRaisesRegex(ValueError, 'version 3'):
|
|
97
|
+
read(2, self.config['cameraEnvironments'])
|
|
98
|
+
original = {'environment': {'sourceVideoSha256': '1' * 64}}
|
|
99
|
+
self.assertEqual(read(2, {'replay': original})['nativeConfig']['cameraEnvironments'], {'replay': original})
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
if __name__ == '__main__':
|
|
103
|
+
unittest.main()
|