node-red-contrib-octopus-intelligent 1.4.0 → 1.6.1

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +487 -408
  2. package/README.md +1004 -980
  3. package/examples/basic-monitoring.json +1 -1
  4. package/examples/ha-dashboard.yaml +602 -486
  5. package/examples/mqtt-integration.json +1 -1
  6. package/examples/node-red-dashboard-flow.json +1287 -0
  7. package/examples/set-preferences.json +1 -1
  8. package/lib/api-metrics.js +31 -31
  9. package/lib/auth.js +20 -20
  10. package/lib/categories/account.js +32 -32
  11. package/lib/categories/applicable-rates.js +127 -91
  12. package/lib/categories/completed-dispatches.js +35 -35
  13. package/lib/categories/electricity.js +146 -133
  14. package/lib/categories/flex-planned-dispatches.js +36 -36
  15. package/lib/categories/free-electricity.js +61 -61
  16. package/lib/categories/gas.js +95 -95
  17. package/lib/categories/home-mini.js +37 -37
  18. package/lib/categories/intelligent.js +155 -124
  19. package/lib/categories/octoplus.js +32 -32
  20. package/lib/categories/saving-sessions.js +64 -64
  21. package/lib/categories/wheel-of-fortune.js +49 -49
  22. package/lib/commands.js +47 -0
  23. package/lib/discovery-retry.js +13 -0
  24. package/lib/discovery.js +92 -85
  25. package/lib/graphql-errors.js +18 -0
  26. package/lib/graphql.js +44 -44
  27. package/lib/http-get-json.js +22 -0
  28. package/lib/payload.js +89 -77
  29. package/lib/poll-tick.js +44 -44
  30. package/lib/preferences.js +32 -0
  31. package/lib/scheduler.js +47 -47
  32. package/lib/sensor-definitions.js +219 -0
  33. package/lib/timezone.js +49 -49
  34. package/lib/update-check.js +38 -0
  35. package/octopus-intelligent.html +218 -205
  36. package/octopus-intelligent.js +1687 -1685
  37. package/package.json +54 -54
@@ -1,64 +1,64 @@
1
- 'use strict';
2
-
3
- // savingSessions moved to api.backend.octopus.energy — the field was removed
4
- // from api.octopus.energy. Requires User-Agent header (set in lib/graphql.js)
5
- // to avoid edge 403 on the backend endpoint.
6
- // octopoints removed from SavingSessionsAccountType — fetch via octoplus category instead.
7
- const QUERY = `
8
- query getSavingSessions($account: String!) {
9
- savingSessions {
10
- events(includeDev: false) {
11
- id code rewardPerKwhInOctoPoints startAt endAt
12
- }
13
- account(accountNumber: $account) {
14
- hasJoinedCampaign
15
- joinedEvents { eventId startAt endAt rewardGivenInOctoPoints }
16
- }
17
- }
18
- }`;
19
-
20
- function buildQuery(account) {
21
- return {
22
- query: QUERY,
23
- variables: { account },
24
- hostname: 'api.backend.octopus.energy'
25
- };
26
- }
27
-
28
- function parseResponse(data) {
29
- const now = new Date();
30
- const ss = data.savingSessions || {};
31
- const acct = ss.account || {};
32
- const events = ss.events || [];
33
-
34
- // Filter to events not yet ended; sort earliest-first; take the first
35
- const upcoming = events
36
- .filter(e => new Date(e.endAt) > now)
37
- .sort((a, b) => new Date(a.startAt) - new Date(b.startAt));
38
- const next = upcoming[0] || null;
39
-
40
- const joinedIds = (acct.joinedEvents || []).map(e => e.eventId);
41
- const isJoined = next ? joinedIds.includes(next.id) : false;
42
-
43
- const inWindow = next
44
- && new Date(next.startAt) <= now
45
- && new Date(next.endAt) > now;
46
-
47
- return {
48
- saving_session_available: next !== null,
49
- saving_session_start: next ? next.startAt : null,
50
- saving_session_end: next ? next.endAt : null,
51
- saving_session_joined: isJoined,
52
- saving_session_window_active: !!inWindow,
53
- saving_session_active: !!(inWindow && isJoined),
54
- saving_sessions_error: null
55
- };
56
- }
57
-
58
- const defaultData = {
59
- saving_session_available: null, saving_session_start: null, saving_session_end: null,
60
- saving_session_joined: null, saving_session_window_active: null, saving_session_active: null,
61
- saving_sessions_error: null
62
- };
63
-
64
- module.exports = { buildQuery, parseResponse, defaultData };
1
+ 'use strict';
2
+
3
+ // savingSessions moved to api.backend.octopus.energy — the field was removed
4
+ // from api.octopus.energy. Requires User-Agent header (set in lib/graphql.js)
5
+ // to avoid edge 403 on the backend endpoint.
6
+ // octopoints removed from SavingSessionsAccountType — fetch via octoplus category instead.
7
+ const QUERY = `
8
+ query getSavingSessions($account: String!) {
9
+ savingSessions {
10
+ events(includeDev: false) {
11
+ id code rewardPerKwhInOctoPoints startAt endAt
12
+ }
13
+ account(accountNumber: $account) {
14
+ hasJoinedCampaign
15
+ joinedEvents { eventId startAt endAt rewardGivenInOctoPoints }
16
+ }
17
+ }
18
+ }`;
19
+
20
+ function buildQuery(account) {
21
+ return {
22
+ query: QUERY,
23
+ variables: { account },
24
+ hostname: 'api.backend.octopus.energy'
25
+ };
26
+ }
27
+
28
+ function parseResponse(data) {
29
+ const now = new Date();
30
+ const ss = data.savingSessions || {};
31
+ const acct = ss.account || {};
32
+ const events = ss.events || [];
33
+
34
+ // Filter to events not yet ended; sort earliest-first; take the first
35
+ const upcoming = events
36
+ .filter(e => new Date(e.endAt) > now)
37
+ .sort((a, b) => new Date(a.startAt) - new Date(b.startAt));
38
+ const next = upcoming[0] || null;
39
+
40
+ const joinedIds = (acct.joinedEvents || []).map(e => e.eventId);
41
+ const isJoined = next ? joinedIds.includes(next.id) : false;
42
+
43
+ const inWindow = next
44
+ && new Date(next.startAt) <= now
45
+ && new Date(next.endAt) > now;
46
+
47
+ return {
48
+ saving_session_available: next !== null,
49
+ saving_session_start: next ? next.startAt : null,
50
+ saving_session_end: next ? next.endAt : null,
51
+ saving_session_joined: isJoined,
52
+ saving_session_window_active: !!inWindow,
53
+ saving_session_active: !!(inWindow && isJoined),
54
+ saving_sessions_error: null
55
+ };
56
+ }
57
+
58
+ const defaultData = {
59
+ saving_session_available: null, saving_session_start: null, saving_session_end: null,
60
+ saving_session_joined: null, saving_session_window_active: null, saving_session_active: null,
61
+ saving_sessions_error: null
62
+ };
63
+
64
+ module.exports = { buildQuery, parseResponse, defaultData };
@@ -1,49 +1,49 @@
1
- 'use strict';
2
-
3
- // wheelOfFortuneSpinsAllowed is the non-deprecated successor to wheelOfFortuneSpins.
4
- // It lives on api.backend.octopus.energy (requires User-Agent header — handled in
5
- // lib/graphql.js). The maxSpinsPerMonth / usedSpinsThisMonth fields from the old
6
- // query were not migrated and return null.
7
- const QUERY = `
8
- query getWheelOfFortuneSpinsAllowed($accountNumber: String!) {
9
- electricity: wheelOfFortuneSpinsAllowed(fuelType: ELECTRICITY, accountNumber: $accountNumber) {
10
- spinsAllowed
11
- }
12
- gas: wheelOfFortuneSpinsAllowed(fuelType: GAS, accountNumber: $accountNumber) {
13
- spinsAllowed
14
- }
15
- }`;
16
-
17
- function buildQuery(account) {
18
- return {
19
- query: QUERY,
20
- variables: { accountNumber: account },
21
- hostname: 'api.backend.octopus.energy'
22
- };
23
- }
24
-
25
- function parseResponse(data) {
26
- const elec = data.electricity || {};
27
- const gas = data.gas || {};
28
- return {
29
- wheel_of_fortune_electricity_spins: elec.spinsAllowed ?? 0,
30
- wheel_of_fortune_electricity_max: null,
31
- wheel_of_fortune_electricity_used: null,
32
- wheel_of_fortune_gas_spins: gas.spinsAllowed ?? 0,
33
- wheel_of_fortune_gas_max: null,
34
- wheel_of_fortune_gas_used: null,
35
- wheel_of_fortune_error: null
36
- };
37
- }
38
-
39
- const defaultData = {
40
- wheel_of_fortune_electricity_spins: null,
41
- wheel_of_fortune_electricity_max: null,
42
- wheel_of_fortune_electricity_used: null,
43
- wheel_of_fortune_gas_spins: null,
44
- wheel_of_fortune_gas_max: null,
45
- wheel_of_fortune_gas_used: null,
46
- wheel_of_fortune_error: null
47
- };
48
-
49
- module.exports = { buildQuery, parseResponse, defaultData };
1
+ 'use strict';
2
+
3
+ // wheelOfFortuneSpinsAllowed is the non-deprecated successor to wheelOfFortuneSpins.
4
+ // It lives on api.backend.octopus.energy (requires User-Agent header — handled in
5
+ // lib/graphql.js). The maxSpinsPerMonth / usedSpinsThisMonth fields from the old
6
+ // query were not migrated and return null.
7
+ const QUERY = `
8
+ query getWheelOfFortuneSpinsAllowed($accountNumber: String!) {
9
+ electricity: wheelOfFortuneSpinsAllowed(fuelType: ELECTRICITY, accountNumber: $accountNumber) {
10
+ spinsAllowed
11
+ }
12
+ gas: wheelOfFortuneSpinsAllowed(fuelType: GAS, accountNumber: $accountNumber) {
13
+ spinsAllowed
14
+ }
15
+ }`;
16
+
17
+ function buildQuery(account) {
18
+ return {
19
+ query: QUERY,
20
+ variables: { accountNumber: account },
21
+ hostname: 'api.backend.octopus.energy'
22
+ };
23
+ }
24
+
25
+ function parseResponse(data) {
26
+ const elec = data.electricity || {};
27
+ const gas = data.gas || {};
28
+ return {
29
+ wheel_of_fortune_electricity_spins: elec.spinsAllowed ?? 0,
30
+ wheel_of_fortune_electricity_max: null,
31
+ wheel_of_fortune_electricity_used: null,
32
+ wheel_of_fortune_gas_spins: gas.spinsAllowed ?? 0,
33
+ wheel_of_fortune_gas_max: null,
34
+ wheel_of_fortune_gas_used: null,
35
+ wheel_of_fortune_error: null
36
+ };
37
+ }
38
+
39
+ const defaultData = {
40
+ wheel_of_fortune_electricity_spins: null,
41
+ wheel_of_fortune_electricity_max: null,
42
+ wheel_of_fortune_electricity_used: null,
43
+ wheel_of_fortune_gas_spins: null,
44
+ wheel_of_fortune_gas_max: null,
45
+ wheel_of_fortune_gas_used: null,
46
+ wheel_of_fortune_error: null
47
+ };
48
+
49
+ module.exports = { buildQuery, parseResponse, defaultData };
@@ -0,0 +1,47 @@
1
+ 'use strict';
2
+ const { validateTime, validateLimit } = require('./preferences');
3
+
4
+ const COMMAND_KEYS = ['set_limit', 'set_time', 'set_timezone', 'set_smart_charging', 'set_charge_cap'];
5
+
6
+ // Turns a msg.payload into independent actions. Supplied values are validated;
7
+ // fallbacks come from the API (confirmed*) and are passed through unvalidated.
8
+ function planCommands(payload, current) {
9
+ const actions = [];
10
+ const errors = [];
11
+ const has = (k) => payload[k] !== undefined && payload[k] !== null;
12
+ const hasCommand = COMMAND_KEYS.some(has);
13
+
14
+ if (has('set_limit') || has('set_time')) {
15
+ let limit = current.confirmedLimit;
16
+ let time = current.confirmedTime;
17
+ let valid = true;
18
+ if (has('set_limit')) {
19
+ const r = validateLimit(payload.set_limit);
20
+ if (r.ok) limit = r.limit; else { errors.push(r.error); valid = false; }
21
+ }
22
+ if (has('set_time')) {
23
+ const r = validateTime(payload.set_time);
24
+ if (r.ok) time = r.time; else { errors.push(r.error); valid = false; }
25
+ }
26
+ if (valid) actions.push({ type: 'preferences', limit, time });
27
+ }
28
+
29
+ if (has('set_timezone')) {
30
+ const tz = payload.set_timezone;
31
+ if (typeof tz === 'string' && tz.trim().length > 0) {
32
+ actions.push({ type: 'timezone', timezone: tz.trim() });
33
+ }
34
+ }
35
+
36
+ if (has('set_smart_charging') && typeof payload.set_smart_charging === 'boolean') {
37
+ actions.push({ type: 'smart_charging', enabled: payload.set_smart_charging });
38
+ }
39
+
40
+ if (has('set_charge_cap') && typeof payload.set_charge_cap === 'boolean') {
41
+ actions.push({ type: 'charge_cap', enabled: payload.set_charge_cap });
42
+ }
43
+
44
+ return { actions, errors, hasCommand };
45
+ }
46
+
47
+ module.exports = { planCommands };
@@ -0,0 +1,13 @@
1
+ // lib/discovery-retry.js
2
+ 'use strict';
3
+
4
+ // Startup discovery retry schedule: quick early retries for transient Kraken errors,
5
+ // then a steady 5-minute cadence until it succeeds.
6
+ const DISCOVERY_RETRY_DELAYS_MS = [30000, 60000, 120000];
7
+ const DISCOVERY_RETRY_STEADY_MS = 300000;
8
+
9
+ function discoveryRetryDelay(attempt) {
10
+ return attempt < DISCOVERY_RETRY_DELAYS_MS.length ? DISCOVERY_RETRY_DELAYS_MS[attempt] : DISCOVERY_RETRY_STEADY_MS;
11
+ }
12
+
13
+ module.exports = { DISCOVERY_RETRY_DELAYS_MS, DISCOVERY_RETRY_STEADY_MS, discoveryRetryDelay };
package/lib/discovery.js CHANGED
@@ -1,85 +1,92 @@
1
- // lib/discovery.js
2
- 'use strict';
3
- const { graphqlPost } = require('./graphql');
4
- const { obtainToken } = require('./auth');
5
-
6
- const DISCOVERY_QUERY = `
7
- query discover($account: String!) {
8
- account(accountNumber: $account) {
9
- electricityAgreements { validFrom }
10
- gasAgreements { validFrom }
11
- properties {
12
- electricityMeterPoints {
13
- mpan
14
- direction
15
- meters {
16
- serialNumber
17
- smartImportElectricityMeter { deviceId }
18
- }
19
- }
20
- gasMeterPoints { mprn meters { serialNumber } }
21
- }
22
- }
23
- devices(accountNumber: $account) {
24
- id
25
- deviceType
26
- status { isSuspended }
27
- }
28
- }`;
29
-
30
- function parseDiscovery(data) {
31
- const acct = data.account || {};
32
- const devices = data.devices || [];
33
- const evDevice = devices.find(d => d.deviceType === 'ELECTRIC_VEHICLES') || null;
34
- const props = (acct.properties || [])[0] || {};
35
- const elecPoints = props.electricityMeterPoints || [];
36
- const gasPoints = props.gasMeterPoints || [];
37
-
38
- // Find import and export meter points by direction. Accounts may have
39
- // either or both. Position in the array is NOT reliable — observed live
40
- // (2026-05-11) that the export meter can appear at index 0.
41
- const importPoint = elecPoints.find(p => p.direction === 'IMPORT') || null;
42
- const exportPoint = elecPoints.find(p => p.direction === 'EXPORT') || null;
43
-
44
- // Home Mini device ID: scan all meter points for smartImportElectricityMeter.
45
- let smartMeterDeviceId = null;
46
- for (const point of elecPoints) {
47
- for (const meter of (point.meters || [])) {
48
- if (meter.smartImportElectricityMeter && meter.smartImportElectricityMeter.deviceId) {
49
- smartMeterDeviceId = meter.smartImportElectricityMeter.deviceId;
50
- break;
51
- }
52
- }
53
- if (smartMeterDeviceId) break;
54
- }
55
-
56
- const firstImportMeter = importPoint && importPoint.meters && importPoint.meters[0] ? importPoint.meters[0] : null;
57
-
58
- return {
59
- hasIntelligent: !!evDevice,
60
- hasElectricity: (acct.electricityAgreements || []).length > 0,
61
- hasGas: (acct.gasAgreements || []).length > 0,
62
- deviceId: evDevice ? evDevice.id : null,
63
- deviceSuspended: evDevice ? evDevice.status.isSuspended : null,
64
- smartMeterDeviceId,
65
- electricityMpan: importPoint ? importPoint.mpan : null,
66
- electricityExportMpan: exportPoint ? exportPoint.mpan : null,
67
- electricitySerial: firstImportMeter ? firstImportMeter.serialNumber : null,
68
- gasMprn: gasPoints[0] ? gasPoints[0].mprn : null,
69
- gasSerial: gasPoints[0] && gasPoints[0].meters[0] ? gasPoints[0].meters[0].serialNumber : null
70
- };
71
- }
72
-
73
- async function discoverProducts(apiKey, account) {
74
- const token = await obtainToken(apiKey);
75
- const response = await graphqlPost({ query: DISCOVERY_QUERY, variables: { account } }, token);
76
- if (response.data.errors) {
77
- throw new Error(`Discovery failed: ${JSON.stringify(response.data.errors)}`);
78
- }
79
- if (!response.data.data) {
80
- throw new Error('Discovery response missing data');
81
- }
82
- return parseDiscovery(response.data.data);
83
- }
84
-
85
- module.exports = { discoverProducts, parseDiscovery };
1
+ // lib/discovery.js
2
+ 'use strict';
3
+ const { graphqlPost } = require('./graphql');
4
+ const { obtainToken } = require('./auth');
5
+ const { onlyDeviceFieldErrors } = require('./graphql-errors');
6
+
7
+ const DISCOVERY_QUERY = `
8
+ query discover($account: String!) {
9
+ account(accountNumber: $account) {
10
+ electricityAgreements { validFrom }
11
+ gasAgreements { validFrom }
12
+ properties {
13
+ electricityMeterPoints {
14
+ mpan
15
+ direction
16
+ meters {
17
+ serialNumber
18
+ smartImportElectricityMeter { deviceId }
19
+ }
20
+ }
21
+ gasMeterPoints { mprn meters { serialNumber } }
22
+ }
23
+ }
24
+ devices(accountNumber: $account) {
25
+ id
26
+ deviceType
27
+ status { isSuspended }
28
+ }
29
+ }`;
30
+
31
+ function parseDiscovery(data) {
32
+ const acct = data.account || {};
33
+ const devices = data.devices || [];
34
+ const evDevice = devices.find(d => d.deviceType === 'ELECTRIC_VEHICLES') || null;
35
+ const props = (acct.properties || [])[0] || {};
36
+ const elecPoints = props.electricityMeterPoints || [];
37
+ const gasPoints = props.gasMeterPoints || [];
38
+
39
+ // Find import and export meter points by direction. Accounts may have
40
+ // either or both. Position in the array is NOT reliable — observed live
41
+ // (2026-05-11) that the export meter can appear at index 0.
42
+ const importPoint = elecPoints.find(p => p.direction === 'IMPORT') || null;
43
+ const exportPoint = elecPoints.find(p => p.direction === 'EXPORT') || null;
44
+
45
+ // Home Mini device ID: scan all meter points for smartImportElectricityMeter.
46
+ let smartMeterDeviceId = null;
47
+ for (const point of elecPoints) {
48
+ for (const meter of (point.meters || [])) {
49
+ if (meter.smartImportElectricityMeter && meter.smartImportElectricityMeter.deviceId) {
50
+ smartMeterDeviceId = meter.smartImportElectricityMeter.deviceId;
51
+ break;
52
+ }
53
+ }
54
+ if (smartMeterDeviceId) break;
55
+ }
56
+
57
+ const firstImportMeter = importPoint && importPoint.meters && importPoint.meters[0] ? importPoint.meters[0] : null;
58
+
59
+ return {
60
+ hasIntelligent: !!evDevice,
61
+ hasElectricity: (acct.electricityAgreements || []).length > 0,
62
+ hasGas: (acct.gasAgreements || []).length > 0,
63
+ deviceId: evDevice ? evDevice.id : null,
64
+ deviceSuspended: evDevice && evDevice.status ? evDevice.status.isSuspended : null,
65
+ smartMeterDeviceId,
66
+ electricityMpan: importPoint ? importPoint.mpan : null,
67
+ electricityExportMpan: exportPoint ? exportPoint.mpan : null,
68
+ electricitySerial: firstImportMeter ? firstImportMeter.serialNumber : null,
69
+ gasMprn: gasPoints[0] ? gasPoints[0].mprn : null,
70
+ gasSerial: gasPoints[0] && gasPoints[0].meters[0] ? gasPoints[0].meters[0].serialNumber : null
71
+ };
72
+ }
73
+
74
+ async function discoverProducts(apiKey, account) {
75
+ const token = await obtainToken(apiKey);
76
+ const response = await graphqlPost({ query: DISCOVERY_QUERY, variables: { account } }, token);
77
+ const errors = response.data.errors;
78
+ if (errors) {
79
+ // Kraken can fail just the per-device status resolver (KT-CT-4360, transient) while
80
+ // returning everything else. Treat that as "suspended unknown" instead of failing
81
+ // discovery (which would leave the node with no scheduler).
82
+ if (!onlyDeviceFieldErrors(errors, response.data.data, 'status')) {
83
+ throw new Error(`Discovery failed: ${JSON.stringify(errors)}`);
84
+ }
85
+ }
86
+ if (!response.data.data) {
87
+ throw new Error('Discovery response missing data');
88
+ }
89
+ return parseDiscovery(response.data.data);
90
+ }
91
+
92
+ module.exports = { discoverProducts, parseDiscovery };
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ // Kraken can fail a single per-device field (e.g. KT-CT-4360) while returning everything else.
4
+ // True when every error sits under `devices[i].<field>` and the device list and those devices
5
+ // are still present — i.e. the failure stayed inside that field and the rest is usable.
6
+ function onlyDeviceFieldErrors(errors, data, field) {
7
+ if (!Array.isArray(errors) || errors.length === 0) return false;
8
+ const devices = data && data.devices;
9
+ if (!Array.isArray(devices)) return false;
10
+ return errors.every((e) => Array.isArray(e.path)
11
+ && e.path.length >= 3
12
+ && e.path[0] === 'devices'
13
+ && Number.isInteger(e.path[1])
14
+ && devices[e.path[1]] != null
15
+ && e.path[2] === field);
16
+ }
17
+
18
+ module.exports = { onlyDeviceFieldErrors };
package/lib/graphql.js CHANGED
@@ -1,44 +1,44 @@
1
- 'use strict';
2
- const https = require('https');
3
- const { version } = require('../package.json');
4
-
5
- // User-Agent is REQUIRED for api.backend.octopus.energy — the default Node.js UA
6
- // is blocked at the edge (403). Sending a real UA on every request keeps both
7
- // the main and backend endpoints reachable from a single transport.
8
- const USER_AGENT = `node-red-contrib-octopus-intelligent/${version}`;
9
-
10
- function graphqlPost(body, token, hostname = 'api.octopus.energy') {
11
- return new Promise((resolve, reject) => {
12
- const payload = JSON.stringify(body);
13
- const headers = {
14
- 'Content-Type': 'application/json',
15
- 'Content-Length': Buffer.byteLength(payload),
16
- 'User-Agent': USER_AGENT
17
- };
18
- // Kraken expects the raw JWT. Both endpoints accept this. Adding a
19
- // "JWT " prefix passes main-endpoint validation but fails sub-resolver
20
- // auth on api.backend.octopus.energy (verified live 2026-05-11).
21
- if (token) headers['Authorization'] = token;
22
- const req = https.request({
23
- hostname,
24
- path: '/v1/graphql/',
25
- method: 'POST',
26
- headers
27
- }, (res) => {
28
- let raw = '';
29
- res.on('data', chunk => raw += chunk);
30
- res.on('end', () => {
31
- try {
32
- resolve({ data: JSON.parse(raw), status: res.statusCode, headers: res.headers });
33
- } catch (e) {
34
- reject(new Error('Failed to parse API response: ' + e.message));
35
- }
36
- });
37
- });
38
- req.on('error', reject);
39
- req.write(payload);
40
- req.end();
41
- });
42
- }
43
-
44
- module.exports = { graphqlPost };
1
+ 'use strict';
2
+ const https = require('https');
3
+ const { version } = require('../package.json');
4
+
5
+ // User-Agent is REQUIRED for api.backend.octopus.energy — the default Node.js UA
6
+ // is blocked at the edge (403). Sending a real UA on every request keeps both
7
+ // the main and backend endpoints reachable from a single transport.
8
+ const USER_AGENT = `node-red-contrib-octopus-intelligent/${version}`;
9
+
10
+ function graphqlPost(body, token, hostname = 'api.octopus.energy') {
11
+ return new Promise((resolve, reject) => {
12
+ const payload = JSON.stringify(body);
13
+ const headers = {
14
+ 'Content-Type': 'application/json',
15
+ 'Content-Length': Buffer.byteLength(payload),
16
+ 'User-Agent': USER_AGENT
17
+ };
18
+ // Kraken expects the raw JWT. Both endpoints accept this. Adding a
19
+ // "JWT " prefix passes main-endpoint validation but fails sub-resolver
20
+ // auth on api.backend.octopus.energy (verified live 2026-05-11).
21
+ if (token) headers['Authorization'] = token;
22
+ const req = https.request({
23
+ hostname,
24
+ path: '/v1/graphql/',
25
+ method: 'POST',
26
+ headers
27
+ }, (res) => {
28
+ let raw = '';
29
+ res.on('data', chunk => raw += chunk);
30
+ res.on('end', () => {
31
+ try {
32
+ resolve({ data: JSON.parse(raw), status: res.statusCode, headers: res.headers });
33
+ } catch (e) {
34
+ reject(new Error('Failed to parse API response: ' + e.message));
35
+ }
36
+ });
37
+ });
38
+ req.on('error', reject);
39
+ req.write(payload);
40
+ req.end();
41
+ });
42
+ }
43
+
44
+ module.exports = { graphqlPost };
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+ const https = require('https');
3
+
4
+ function httpGetJson(url) {
5
+ return new Promise((resolve, reject) => {
6
+ const req = https.get(url, res => {
7
+ if (res.statusCode < 200 || res.statusCode >= 300) {
8
+ res.resume();
9
+ return reject(new Error(`HTTP ${res.statusCode}`));
10
+ }
11
+ let body = '';
12
+ res.on('data', chunk => { body += chunk; });
13
+ res.on('end', () => {
14
+ try { resolve(JSON.parse(body)); }
15
+ catch (e) { reject(new Error(`JSON parse: ${e.message}`)); }
16
+ });
17
+ });
18
+ req.on('error', reject);
19
+ });
20
+ }
21
+
22
+ module.exports = httpGetJson;