From 5b303a46a0b5be089c9b01803a45067e28cc74d1 Mon Sep 17 00:00:00 2001 From: Stefan Nebel Date: Thu, 8 Oct 2026 23:52:40 +0200 Subject: [PATCH] feat: add token status and prepare 2.1.0 Expose GET /v1/token/status as client.token.status(). It returns the token's display name, granted scopes and expiry, needs no scope and changes no data. Known scopes are typed as TokenScope; a scope added by a newer API stays a plain string instead of failing the response. Vendor the shared contract cases for the new operation from the Python client and compare expiresAt as an instant. --- README.md | 1 + contracts/README.md | 12 ++-- contracts/cases/errors.json | 37 +++++++++++ contracts/cases/token.json | 123 ++++++++++++++++++++++++++++++++++++ contracts/schema.json | 22 ++++++- contracts/source.json | 9 +-- package-lock.json | 4 +- package.json | 2 +- scripts/check-package.mjs | 3 +- src/client.ts | 3 + src/decoders.ts | 9 +++ src/models.ts | 23 +++++++ src/resources/token.ts | 15 +++++ tests/client.test.mjs | 10 +++ tests/contracts.test.mjs | 2 + 15 files changed, 262 insertions(+), 13 deletions(-) create mode 100644 contracts/cases/token.json create mode 100644 src/resources/token.ts diff --git a/README.md b/README.md index 734bb1d..aede391 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ exports return `Uint8Array`. The server handles calendar boundaries and rounding | `meterReadings` | `list`, `create`, `delete`, `export` | | `environments` | `list`, `get`, `create`, `delete`, `createEntry`, `deleteEntry` | | `calculations` | `dailyValues`, `extrapolations` | +| `token` | `status` | See [API usage](https://github.com/energy-tracker/api-client-typescript/blob/main/docs/api.md) for options and errors. diff --git a/contracts/README.md b/contracts/README.md index 1896390..1a4d38f 100644 --- a/contracts/README.md +++ b/contracts/README.md @@ -31,13 +31,17 @@ test and release checks. No API token, live backend or sibling checkout is neede present, `retryAfter` in seconds. Exception class names and local wording are language-specific. Assert exactly one request, including on errors/redirects. -Compare `timestamp`, `date`, `lastUpdatedAt`, `from`, `to`, `updatedAfter` and -`updatedBefore` as offset-aware instants. `Z` and equivalent offsets/fractional -spellings are interchangeable. Do not round to calendar boundaries. Compare -all other values directly, preserving decimal precision and list order. +Compare `timestamp`, `date`, `lastUpdatedAt`, `expiresAt`, `from`, `to`, +`updatedAfter` and `updatedBefore` as offset-aware instants. `Z` and equivalent +offsets/fractional spellings are interchangeable. Do not round to calendar +boundaries. Compare all other values directly, preserving decimal precision and +list order. Token scopes compare as strings; scopes unknown to an SDK pass +through unchanged. The wire examples were checked against the Public API controllers and DTOs in [energy-tracker-core at fcc269a06184426caf64c882291d4209be57a723](https://github.com/StefaniOSApps/energy-tracker-core/tree/fcc269a06184426caf64c882291d4209be57a723/backend/src/app/public-api). +The token status examples were checked against +[energy-tracker-core at 969b1b722d3e56505c86ecdd098e1bcebaff90b3](https://github.com/StefaniOSApps/energy-tracker-core/tree/969b1b722d3e56505c86ecdd098e1bcebaff90b3/backend/src/app/public-api). Error/redirect/malformed-response cases additionally specify SDK behavior; their messages are illustrative, not fixed backend wording. These mocked responses do not verify server calculations, validation rules or authorization scopes. diff --git a/contracts/cases/errors.json b/contracts/cases/errors.json index 898462b..5bb4cb5 100644 --- a/contracts/cases/errors.json +++ b/contracts/cases/errors.json @@ -521,6 +521,43 @@ } } }, + { + "id": "token-status-wrong-status", + "operation": "token.status", + "input": {}, + "request": { + "method": "GET", + "path": "/v1/token/status", + "query": {}, + "headers": { + "Authorization": "Bearer contract-test-token" + }, + "body": {} + }, + "response": { + "status": 201, + "headers": { + "Content-Type": "application/json" + }, + "body": { + "json": { + "displayName": "Home Assistant Zählerschrank", + "scopes": [ + "write:meter-reading", + "read:measuring-device" + ], + "expiresAt": "2027-01-01T00:00:00.000Z" + } + } + }, + "expected": { + "error": { + "kind": "api", + "status": 201, + "messages": [] + } + } + }, { "id": "readings-create-error-400", "operation": "meterReadings.create", diff --git a/contracts/cases/token.json b/contracts/cases/token.json new file mode 100644 index 0000000..e215f87 --- /dev/null +++ b/contracts/cases/token.json @@ -0,0 +1,123 @@ +{ + "schemaVersion": 1, + "cases": [ + { + "id": "token-status", + "operation": "token.status", + "input": {}, + "request": { + "method": "GET", + "path": "/v1/token/status", + "query": {}, + "headers": { + "Authorization": "Bearer contract-test-token" + }, + "body": {} + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "body": { + "json": { + "displayName": "Home Assistant Zählerschrank", + "scopes": [ + "write:meter-reading", + "read:measuring-device" + ], + "expiresAt": "2027-01-01T00:00:00.000Z" + } + } + }, + "expected": { + "result": { + "displayName": "Home Assistant Zählerschrank", + "scopes": [ + "write:meter-reading", + "read:measuring-device" + ], + "expiresAt": "2027-01-01T00:00:00.000Z" + } + } + }, + { + "id": "token-status-no-expiry", + "operation": "token.status", + "input": {}, + "request": { + "method": "GET", + "path": "/v1/token/status", + "query": {}, + "headers": { + "Authorization": "Bearer contract-test-token" + }, + "body": {} + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "body": { + "json": { + "displayName": "Write only", + "scopes": [ + "write:meter-reading" + ], + "expiresAt": null + } + } + }, + "expected": { + "result": { + "displayName": "Write only", + "scopes": [ + "write:meter-reading" + ], + "expiresAt": null + } + } + }, + { + "id": "token-status-unknown-scope", + "operation": "token.status", + "input": {}, + "request": { + "method": "GET", + "path": "/v1/token/status", + "query": {}, + "headers": { + "Authorization": "Bearer contract-test-token" + }, + "body": {} + }, + "response": { + "status": 200, + "headers": { + "Content-Type": "application/json" + }, + "body": { + "json": { + "displayName": "Newer backend", + "scopes": [ + "meter-reading", + "read:future-resource" + ], + "expiresAt": null + } + } + }, + "expected": { + "result": { + "displayName": "Newer backend", + "scopes": [ + "meter-reading", + "read:future-resource" + ], + "expiresAt": null + } + } + } + ] +} diff --git a/contracts/schema.json b/contracts/schema.json index 9856bba..0672bb3 100644 --- a/contracts/schema.json +++ b/contracts/schema.json @@ -42,7 +42,8 @@ "environments.createEntry", "environments.deleteEntry", "calculations.dailyValues", - "calculations.extrapolations" + "calculations.extrapolations", + "token.status" ] }, "input": { @@ -714,6 +715,25 @@ } } } + }, + { + "if": { + "properties": { + "operation": { + "const": "token.status" + } + } + }, + "then": { + "properties": { + "input": { + "type": "object", + "properties": {}, + "required": [], + "additionalProperties": false + } + } + } } ] }, diff --git a/contracts/source.json b/contracts/source.json index 178a85c..274217e 100644 --- a/contracts/source.json +++ b/contracts/source.json @@ -1,13 +1,14 @@ { "repository": "https://github.com/energy-tracker/api-client-python", - "commit": "6cf17f0631e3f71038da3ac06ce91e82965e1cf2", + "commit": "365416bfb5e559d548d94f0c0d5dae22c11c3504", "sha256": { - "README.md": "985242aa12e06502b0dcbdf75ec3b95c8fd840dee4a1f309620f1b338e64a59a", + "README.md": "e2431d82e993a3529e81651303e3c0c741c65a93c8aa59673dc08fcf2bdb9e17", "cases/calculations.json": "0065dc017f173c15b21dbc3b40c3e37d1f1ea80b957669ad50df20f9e888efe0", "cases/devices.json": "7324964ac126b43b1d6070cf685ddae4e5659f6edbc8c934af34a796453bf15b", "cases/environments.json": "c069c180405e1414029fe496e46f0272242e6f4d421b1754f16e442307f5cdd8", - "cases/errors.json": "5bdeeaa2bdfe5b042ef2fa15bc53d06b422547a9a5535c85cc82c09b382fe721", + "cases/errors.json": "aaf5d43da99ac791976bce6ddd3b3b70d0b4c10ab808b802d1589c5f474776a6", "cases/meter-readings.json": "f6ab1fd908cdabc69c2238c8c91188e5e862186716cb4bdc63f7f4195ffd115c", - "schema.json": "e91982f7d62a1bae6d48f5c1614fcf1cda9f3e27c32249aee602c2cfa5c9dc2d" + "cases/token.json": "be9df153140912a745a48dbf101208b5c6f913781de340905f4980995809a2d8", + "schema.json": "fe20b470fc5103bc84e8b2f45931fcc1904b3110a7d9e972c91fe5e71b2b5234" } } diff --git a/package-lock.json b/package-lock.json index 8dd24f0..688cbf2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@energy-tracker/api-client", - "version": "2.0.0", + "version": "2.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@energy-tracker/api-client", - "version": "2.0.0", + "version": "2.1.0", "license": "MIT", "devDependencies": { "@types/node": "^20.0.0", diff --git a/package.json b/package.json index e5908e6..b1effe0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@energy-tracker/api-client", - "version": "2.0.0", + "version": "2.1.0", "description": "Typed async client for the Energy Tracker public API", "license": "MIT", "author": "Stefan Nebel", diff --git a/scripts/check-package.mjs b/scripts/check-package.mjs index 15e88cc..889dd02 100644 --- a/scripts/check-package.mjs +++ b/scripts/check-package.mjs @@ -53,12 +53,13 @@ try { const esm = `import { EnergyTrackerClient, ValidationError } from '${pkg.name}'; import { createRequire } from 'node:module'; const cjs = createRequire(import.meta.url)('${pkg.name}'); if (EnergyTrackerClient !== cjs.EnergyTrackerClient || ValidationError !== cjs.ValidationError) throw Error('Module identity mismatch');`; await writeFile(join(temp, 'smoke.mjs'), esm); execFileSync(process.execPath, [join(temp, 'smoke.mjs')], { cwd: temp, stdio: 'inherit' }); - const consumer = `import { EnergyTrackerClient, CalculationInterval, type MeterReadingDto } from '${pkg.name}'; + const consumer = `import { EnergyTrackerClient, CalculationInterval, TokenScope, type MeterReadingDto } from '${pkg.name}'; const client = new EnergyTrackerClient({accessToken: 'test'}); const result: Promise = client.meterReadings.list('device'); void result; void client.meterReadings.create('device', {value: '9999999999.999999', timestamp: new Date()}); void client.calculations.extrapolations('device', {interval: CalculationInterval.MONTH}); +void client.token.status().then((status) => status.scopes.includes(TokenScope.WRITE_METER_READING) || status.scopes.includes('read:future-resource')); // @ts-expect-error Meter values must not lose precision through a number. void client.meterReadings.create('device', {value: 123.45}); // @ts-expect-error Unsupported intervals must be rejected by the type system. diff --git a/src/client.ts b/src/client.ts index afd576b..10311e4 100644 --- a/src/client.ts +++ b/src/client.ts @@ -2,6 +2,7 @@ import { CalculationResource } from './resources/calculations.js'; import { DeviceResource } from './resources/devices.js'; import { EnvironmentResource } from './resources/environments.js'; import { MeterReadingResource } from './resources/meter-readings.js'; +import { TokenResource } from './resources/token.js'; import { Transport } from './transport.js'; import type { ClientOptions } from './transport.js'; @@ -10,6 +11,7 @@ export class EnergyTrackerClient { readonly meterReadings: MeterReadingResource; readonly environments: EnvironmentResource; readonly calculations: CalculationResource; + readonly token: TokenResource; constructor(options: ClientOptions) { const transport = new Transport(options); @@ -17,5 +19,6 @@ export class EnergyTrackerClient { this.meterReadings = new MeterReadingResource(transport); this.environments = new EnvironmentResource(transport); this.calculations = new CalculationResource(transport); + this.token = new TokenResource(transport); } } diff --git a/src/decoders.ts b/src/decoders.ts index dbbd9da..ecc93d3 100644 --- a/src/decoders.ts +++ b/src/decoders.ts @@ -3,6 +3,7 @@ import type { DeviceSummaryDto, EnvironmentRecordDto, MeterReadingDto, + TokenStatusDto, } from './models.js'; function object(value: unknown): Record { @@ -85,3 +86,11 @@ export function calculation(value: unknown): CalculationPointDto { expectedDuration: number(data.expectedDuration, true), }; } +export function tokenStatus(value: unknown): TokenStatusDto { + const data = object(value); + return { + displayName: string(data.displayName), + scopes: list(string)(data.scopes), + expiresAt: data.expiresAt == null ? null : date(data.expiresAt), + }; +} diff --git a/src/models.ts b/src/models.ts index 9192b71..4bba9cd 100644 --- a/src/models.ts +++ b/src/models.ts @@ -27,6 +27,23 @@ export const CalculationInterval = { export type CalculationInterval = (typeof CalculationInterval)[keyof typeof CalculationInterval]; export const ExtrapolationMethod = { STANDARD: 'standard' } as const; export type ExtrapolationMethod = (typeof ExtrapolationMethod)[keyof typeof ExtrapolationMethod]; +export const TokenScope = { + READ_DAILY_VALUES: 'read:daily-values', + READ_EXTRAPOLATION: 'read:extrapolation', + METER_READING: 'meter-reading', + READ_METER_READING: 'read:meter-reading', + WRITE_METER_READING: 'write:meter-reading', + DELETE_METER_READING: 'delete:meter-reading', + MEASURING_DEVICE: 'measuring-device', + READ_MEASURING_DEVICE: 'read:measuring-device', + WRITE_MEASURING_DEVICE: 'write:measuring-device', + DELETE_MEASURING_DEVICE: 'delete:measuring-device', + ENVIRONMENT_RECORD: 'environment-record', + READ_ENVIRONMENT_RECORD: 'read:environment-record', + WRITE_ENVIRONMENT_RECORD: 'write:environment-record', + DELETE_ENVIRONMENT_RECORD: 'delete:environment-record', +} as const; +export type TokenScope = (typeof TokenScope)[keyof typeof TokenScope]; export interface DeviceSummaryDto { readonly id: string; @@ -86,6 +103,12 @@ export interface CalculationPointDto { readonly expectedValue: number; readonly expectedDuration: number; } +export interface TokenStatusDto { + readonly displayName: string; + /** A scope added by a newer API is kept as a plain string. */ + readonly scopes: readonly (TokenScope | (string & {}))[]; + readonly expiresAt: Date | null; +} export interface RequestOptions { signal?: AbortSignal; diff --git a/src/resources/token.ts b/src/resources/token.ts new file mode 100644 index 0000000..fba2253 --- /dev/null +++ b/src/resources/token.ts @@ -0,0 +1,15 @@ +import { tokenStatus } from '../decoders.js'; +import type { RequestOptions, TokenStatusDto } from '../models.js'; +import type { Transport } from '../transport.js'; + +export class TokenResource { + constructor(private readonly transport: Transport) {} + + /** Needs no scope and changes no data. Limited to 5 requests per 5 minutes; do not poll. */ + async status(options: RequestOptions = {}): Promise { + return this.transport.request( + { method: 'GET', path: '/v1/token/status', status: 200, signal: options.signal }, + tokenStatus, + ); + } +} diff --git a/tests/client.test.mjs b/tests/client.test.mjs index 10b6db4..306a0dc 100644 --- a/tests/client.test.mjs +++ b/tests/client.test.mjs @@ -330,6 +330,16 @@ test('meter-reading response must preserve a decimal string', async (t) => { api.EnergyTrackerAPIError, ); }); +for (const scopes of ['write:meter-reading', ['write:meter-reading', 1], undefined]) { + test(`token status rejects scopes ${JSON.stringify(scopes)}`, async (t) => { + const baseUrl = await serve(t, (req, res) => + res + .writeHead(200, { 'Content-Type': 'application/json' }) + .end(JSON.stringify({ displayName: 'Token', scopes, expiresAt: null })), + ); + await assert.rejects(() => client({ baseUrl }).token.status(), api.EnergyTrackerAPIError); + }); +} test('CSV error responses still expose API messages', async (t) => { const baseUrl = await serve(t, (req, res) => res diff --git a/tests/contracts.test.mjs b/tests/contracts.test.mjs index d7bca70..8c6666b 100644 --- a/tests/contracts.test.mjs +++ b/tests/contracts.test.mjs @@ -23,6 +23,7 @@ const dates = new Set([ 'timestamp', 'date', 'lastUpdatedAt', + 'expiresAt', 'from', 'to', 'updatedAfter', @@ -71,6 +72,7 @@ const operations = { 'calculations.dailyValues': (c, { deviceId, ...i }) => c.calculations.dailyValues(deviceId, i), 'calculations.extrapolations': (c, { deviceId, ...i }) => c.calculations.extrapolations(deviceId, i), + 'token.status': (c) => c.token.status(), }; const errors = { validation: api.ValidationError,