ituran-axi 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/NOTICE +13 -0
- package/README.md +149 -2
- package/dist/account.js +86 -0
- package/dist/auth.js +244 -0
- package/dist/bin/ituran-axi.js +17 -0
- package/dist/cli/parse.js +70 -0
- package/dist/cli/run.js +520 -0
- package/dist/cli/table.js +17 -0
- package/dist/commands/catalog.js +187 -0
- package/dist/commands/centers.js +80 -0
- package/dist/commands/common.js +267 -0
- package/dist/commands/drivers.js +118 -0
- package/dist/commands/home.js +42 -0
- package/dist/commands/places.js +151 -0
- package/dist/commands/readings.js +343 -0
- package/dist/commands/reports.js +492 -0
- package/dist/commands/trips.js +328 -0
- package/dist/commands/vehicles.js +366 -0
- package/dist/config.js +57 -0
- package/dist/errors.js +124 -0
- package/dist/geo.js +31 -0
- package/dist/http.js +177 -0
- package/dist/json.js +50 -0
- package/dist/output/text.js +49 -0
- package/dist/output/toon.js +82 -0
- package/dist/pace.js +33 -0
- package/dist/plates.js +10 -0
- package/dist/time.js +222 -0
- package/dist/version.js +2 -0
- package/package.json +54 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ituran-axi contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/NOTICE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
ituran-axi
|
|
2
|
+
Copyright (c) 2026 ituran-axi contributors. MIT License; see LICENSE.
|
|
3
|
+
|
|
4
|
+
Parts of src/auth.ts, src/json.ts, src/time.ts and src/commands/reports.ts are
|
|
5
|
+
ported from ituran-mcp (https://github.com/ituranlabs/ituran-mcp), MIT License,
|
|
6
|
+
Copyright (c) 2026 Ituran: the identity grants and their
|
|
7
|
+
minutes-based expiry, parsing of integers above 2^53, Windows time zone names,
|
|
8
|
+
and the operational report cursor rules.
|
|
9
|
+
|
|
10
|
+
Runtime dependency: @toon-format/toon 4.4.0, MIT License.
|
|
11
|
+
|
|
12
|
+
Ituran is a trademark of Ituran Location and Control Ltd. This project is not
|
|
13
|
+
made or endorsed by Ituran.
|
package/README.md
CHANGED
|
@@ -1,3 +1,150 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ituran-axi
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/comisai/ituran-axi/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/ituran-axi)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
A read-only command-line tool that lets AI agents read Ituran vehicle tracking: vehicles and their positions, trips, drivers, saved places, events, alerts, sensor readings, reports and safety grades.
|
|
8
|
+
|
|
9
|
+
ituran-axi is an AXI, an [agent experience interface](https://axi.md). Every command:
|
|
10
|
+
- prints compact [TOON](https://github.com/toon-format/toon) text on stdout, bounded in size;
|
|
11
|
+
- refuses bad input and says exactly what is wrong;
|
|
12
|
+
- ends with hints for the next command, as a TOON list, so the whole output decodes as one document;
|
|
13
|
+
- only reads. It never changes Ituran settings or sends commands to a vehicle.
|
|
14
|
+
|
|
15
|
+
It replaces [`ituran-mcp`](https://github.com/ituranlabs/ituran-mcp) for agents that have a shell: 24 commands instead of 152 tool schemas, which cost about 43,000 tokens per conversation. It was built to run inside Comis, behind the Comis Gate, and it also works on its own.
|
|
16
|
+
|
|
17
|
+
> **Status:** early development (0.x). Every command is tested end to end against the production Ituran API.
|
|
18
|
+
|
|
19
|
+
## Requirements
|
|
20
|
+
|
|
21
|
+
- Node.js 22.18 or later.
|
|
22
|
+
- An Ituran fleet account with API access. Use a service account without two-step sign-in.
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npm install -g ituran-axi
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Each release is published from GitHub Actions with [npm provenance](https://docs.npmjs.com/generating-provenance-statements), so you can check that it was built from this repository. To run from source instead, see [Development](#development).
|
|
31
|
+
|
|
32
|
+
## Configure
|
|
33
|
+
|
|
34
|
+
| Variable | Meaning |
|
|
35
|
+
| --- | --- |
|
|
36
|
+
| `ITURAN_USERNAME`, `ITURAN_PASSWORD` | The account to sign in with |
|
|
37
|
+
| `ITURAN_TOKEN` | A bearer token, used instead of a username and password. Inside Comis this is the Gate's placeholder, and nothing else is set. |
|
|
38
|
+
| `ITURAN_URL` | The API root. The default is `https://api.ituran.com/api/v2`. `ITURAN_GLOBAL_BASE_URL`, the name `ituran-mcp` uses, also works. |
|
|
39
|
+
|
|
40
|
+
**Sign-in is cached.** Ituran blocks addresses that sign in again and again (HTTP 474), and a command-line tool runs once per command. So ituran-axi keeps the token in `~/.local/state/ituran-axi/` (directory mode 0700, file mode 0600), reuses it for its lifetime, and refreshes it. `ituran-axi logout` deletes it. With `ITURAN_TOKEN` set, ituran-axi never signs in.
|
|
41
|
+
|
|
42
|
+
## Usage
|
|
43
|
+
|
|
44
|
+
```text
|
|
45
|
+
ituran-axi home view: account, time zone, vehicles, next steps
|
|
46
|
+
ituran-axi vehicles [<text>] list, or find by plate digits, name, make or model
|
|
47
|
+
ituran-axi vehicle <plate> last position with address, current driver, saved places
|
|
48
|
+
ituran-axi where [<plate>...] [--all] [--stale 2h] [--near <lat,lon> [--within <km>]]
|
|
49
|
+
ituran-axi trips [<plate>...] [window] trips, matched by their end time
|
|
50
|
+
ituran-axi trip <id> [--points] [--safety] [--speeding]
|
|
51
|
+
ituran-axi totals [<plate>] [window] trip totals for the account or one vehicle
|
|
52
|
+
ituran-axi odometer <plate>... | --all GPS odometer estimates with their reliability
|
|
53
|
+
ituran-axi centers [--near <plate|lat,lon>] Ituran service centers, nearest first
|
|
54
|
+
ituran-axi drivers [<text>] | driver <id>
|
|
55
|
+
ituran-axi places [<text>] | place <id> [--vehicles]
|
|
56
|
+
ituran-axi groups [<id>]
|
|
57
|
+
ituran-axi events [--all] | event <id> event states, and the vehicles in each now
|
|
58
|
+
ituran-axi alerts [--plate <plate>] alert definitions
|
|
59
|
+
ituran-axi diagnostics <plate>... | --all [--names a,b] [--history --date <d>]
|
|
60
|
+
ituran-axi report daily|periodic|idle [<plate>...] [--drivers] [window]
|
|
61
|
+
ituran-axi report speed|events|engine|full|diagnostics|heat-map <plate>... [window] [--over <km/h>]
|
|
62
|
+
ituran-axi safety [totals|vehicles|drivers|groups|periodic|ubi-vehicles|ubi-drivers] [window]
|
|
63
|
+
ituran-axi maintenance [<plate>] [--types]
|
|
64
|
+
ituran-axi temps [current|history <plate>|breaches]
|
|
65
|
+
ituran-axi logout
|
|
66
|
+
ituran-axi help [<command>] every flag of a command
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
A **window** is `--since 90m|24h|7d`, `--from <t> [--to <t>]`, or `--date YYYY-MM-DD`. Times are local to the account's time zone, which the home view shows, and take the form `YYYY-MM-DD` or `YYYY-MM-DDTHH:mm`. **Lists** take `--limit`, `--page`, `--fields` and `--full`.
|
|
70
|
+
|
|
71
|
+
```console
|
|
72
|
+
$ ituran-axi where --limit 3
|
|
73
|
+
summary: 13 vehicles · 9 parking · 4 driving · 1 last seen over 24h ago
|
|
74
|
+
zone: Asia/Jerusalem
|
|
75
|
+
vehicles[3]{plate,age,status,speed,address}:
|
|
76
|
+
"12345678",3m,driving,62,"0 Example Street, Tel Aviv"
|
|
77
|
+
"23456789",3m,parking,0,"1 Example Street, Tel Aviv"
|
|
78
|
+
"34567890",3m,parking,0,"2 Example Street, Tel Aviv"
|
|
79
|
+
help[3]:
|
|
80
|
+
- Run `ituran-axi where --all --page 2 --limit 3` for the next 3
|
|
81
|
+
- Run `ituran-axi vehicle <plate>` for one vehicle's driver and saved places
|
|
82
|
+
- Run `ituran-axi trips <plate> --since 24h` for where it went
|
|
83
|
+
|
|
84
|
+
$ ituran-axi vehicle 00000000
|
|
85
|
+
message: "Ituran found no vehicle 00000000: Entity was not found license_plate: 00000000"
|
|
86
|
+
code: not_found
|
|
87
|
+
usage: "ituran-axi vehicle <plate> [--full]"
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
[`docs/recipes.md`](docs/recipes.md) has tested shell combinations for common questions about the vehicles.
|
|
91
|
+
|
|
92
|
+
### Ituran's own rules
|
|
93
|
+
|
|
94
|
+
ituran-axi handles these, and says so in its output where it matters:
|
|
95
|
+
- Trips are matched by their end time, and appear up to a few hours after they end.
|
|
96
|
+
- Ituran fails a month of trips for the whole account in one request. ituran-axi reads a window longer than 7 days a week at a time, newest week first, and joins the pages.
|
|
97
|
+
- BI reports ignore plate filters, so ituran-axi filters them itself.
|
|
98
|
+
- Operational reports take at most 5 plates and less than 3 days per request. ituran-axi splits the request, walks the pages and removes repeated rows.
|
|
99
|
+
- Alert lists repeat rows, which are removed and counted.
|
|
100
|
+
- Keypad driver codes above 2^53 stay exact.
|
|
101
|
+
- A model year or odometer of 0 means "not set".
|
|
102
|
+
|
|
103
|
+
## Output and errors
|
|
104
|
+
|
|
105
|
+
- **Size:** a value is cut at 500 characters and the whole output at about 4,000. `--full` lifts both limits, up to 256 KB.
|
|
106
|
+
- **Text safety:** invisible and bidirectional control characters are shown as `\uXXXX`, and values that look like credentials are withheld.
|
|
107
|
+
- **Personal data:** phone numbers and e-mail addresses appear only with `--full` or `--fields`.
|
|
108
|
+
- **Errors** print `message`, `code` and `usage` on stdout.
|
|
109
|
+
- **Exit codes:** 0 on success, 1 on an error, 2 on a usage error.
|
|
110
|
+
|
|
111
|
+
| Code | Meaning |
|
|
112
|
+
| --- | --- |
|
|
113
|
+
| `usage` | The command line is wrong; `usage` shows the right form |
|
|
114
|
+
| `not_connected` | No token, and no username and password |
|
|
115
|
+
| `auth_failed`, `two_step_required` | Ituran refused the sign-in, or asked for a second step |
|
|
116
|
+
| `access_blocked` | Ituran blocked this address (HTTP 474). Do not retry. |
|
|
117
|
+
| `not_visible`, `not_found`, `not_tracked` | The plate or record is not in this account, or Ituran keeps no trips for it |
|
|
118
|
+
| `not_entitled`, `feature_off`, `needs_app_id` | This account does not include that service |
|
|
119
|
+
| `rejected` | Ituran refused the request; its message is shown |
|
|
120
|
+
| `rate_limited`, `ituran_error`, `unreachable` | Ituran limited the request, failed, or could not be reached |
|
|
121
|
+
| `reconnect_needed`, `refused` | Inside Comis: the owner must reconnect, or the Gate refused |
|
|
122
|
+
| `output_too_large` | Even `--full` would exceed 256 KB; narrow the query |
|
|
123
|
+
| `internal_error` | A bug in ituran-axi; please [report it](https://github.com/comisai/ituran-axi/issues) |
|
|
124
|
+
|
|
125
|
+
## Comis
|
|
126
|
+
|
|
127
|
+
Comis ships `ituran-axi` in its `apps` pack, with the `ituran-read` skill and the `ituran` Gate service in its own repository. Inside Comis, the Gate signs in to Ituran and holds the token, and the agent's workbench never sees the password or the token. [`test/fixtures/comis-ituran-entry.json`](test/fixtures/comis-ituran-entry.json) is a copy of that Gate service; `test/contract/gate-entry.test.ts` checks that every request the AXI sends gets the token as a read, and that sign-in, device commands and writes are denied.
|
|
128
|
+
|
|
129
|
+
## Development
|
|
130
|
+
|
|
131
|
+
```sh
|
|
132
|
+
git clone https://github.com/comisai/ituran-axi.git && cd ituran-axi
|
|
133
|
+
npm ci
|
|
134
|
+
npm run check # type-check, lint, unit and contract tests against a fake Ituran
|
|
135
|
+
npm run build # dist/bin/ituran-axi.js
|
|
136
|
+
npm run test:dist # contract and AXI-principle tests against the built CLI
|
|
137
|
+
npm link # optional: put this build on your PATH as ituran-axi
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
The live tests against the real Ituran API are opt-in, read-only, and need your own account; see [CONTRIBUTING.md](CONTRIBUTING.md#live-tests). The design and plans are in [`docs/`](docs/ituran-axi-design.md).
|
|
141
|
+
|
|
142
|
+
## Contributing
|
|
143
|
+
|
|
144
|
+
Contributions are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) first, and follow the [Code of Conduct](CODE_OF_CONDUCT.md). Report security issues privately, as described in [SECURITY.md](SECURITY.md).
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
MIT; see [LICENSE](LICENSE). Third-party notices are in [NOTICE](NOTICE).
|
|
149
|
+
|
|
150
|
+
Ituran is a trademark of Ituran Location and Control Ltd. This project is not affiliated with or endorsed by Ituran.
|
package/dist/account.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// The account: who is signed in, the zone its times are in, and the services
|
|
2
|
+
// a read has found unavailable. Derived from Ituran and kept for a day in the
|
|
3
|
+
// cache directory; deleting it costs one users/me read.
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { join } from 'node:path';
|
|
8
|
+
import { zoneOf } from './time.js';
|
|
9
|
+
const MAX_AGE_MS = 24 * 3600_000;
|
|
10
|
+
export function cacheDir(settings, env) {
|
|
11
|
+
const root = env.XDG_CACHE_HOME || join(env.HOME || homedir(), '.cache');
|
|
12
|
+
const who = settings.auth.kind === 'password'
|
|
13
|
+
? `user:${settings.auth.user}`
|
|
14
|
+
: `token:${createHash('sha256').update(settings.auth.token).digest('hex')}`;
|
|
15
|
+
const key = createHash('sha256')
|
|
16
|
+
.update(`${settings.url}|${who}`)
|
|
17
|
+
.digest('hex')
|
|
18
|
+
.slice(0, 16);
|
|
19
|
+
return join(root, 'ituran-axi', key);
|
|
20
|
+
}
|
|
21
|
+
export function readJson(file) {
|
|
22
|
+
try {
|
|
23
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** Write atomically; a cache that cannot be written is only a slower next run. */
|
|
30
|
+
export function writeJson(dir, name, value) {
|
|
31
|
+
try {
|
|
32
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
33
|
+
const file = join(dir, name);
|
|
34
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
35
|
+
writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 });
|
|
36
|
+
renameSync(tmp, file);
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
/* read-only or full disk: carry on without the cache */
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const str = (v) => typeof v === 'string' && v ? v : null;
|
|
43
|
+
export async function loadAccount(client, dir, now, fresh = false) {
|
|
44
|
+
const cached = readJson(join(dir, 'account.json'));
|
|
45
|
+
if (!fresh &&
|
|
46
|
+
cached &&
|
|
47
|
+
now.getTime() - Date.parse(cached.fetchedAt) < MAX_AGE_MS &&
|
|
48
|
+
now.getTime() >= Date.parse(cached.fetchedAt)) {
|
|
49
|
+
return cached;
|
|
50
|
+
}
|
|
51
|
+
const me = ((await client.read({
|
|
52
|
+
method: 'GET',
|
|
53
|
+
path: `${client.settings.basePath}/users/me`,
|
|
54
|
+
ctx: { what: 'the signed-in user' },
|
|
55
|
+
})) ?? {});
|
|
56
|
+
const localization = (me.localization ?? {});
|
|
57
|
+
const zoneName = str(localization.timezone_name);
|
|
58
|
+
const account = {
|
|
59
|
+
customer: str(me.customer_name),
|
|
60
|
+
user: str(me.user_name),
|
|
61
|
+
role: str(me.role_name),
|
|
62
|
+
zoneName,
|
|
63
|
+
zone: zoneOf(zoneName ?? undefined),
|
|
64
|
+
unavailable: cached?.unavailable ?? {},
|
|
65
|
+
fetchedAt: now.toISOString(),
|
|
66
|
+
};
|
|
67
|
+
writeJson(dir, 'account.json', account);
|
|
68
|
+
return account;
|
|
69
|
+
}
|
|
70
|
+
/** Remember that a service answered as unavailable, for the home view. */
|
|
71
|
+
export function noteUnavailable(dir, service, code) {
|
|
72
|
+
const cached = readJson(join(dir, 'account.json'));
|
|
73
|
+
if (!cached || cached.unavailable[service] === code)
|
|
74
|
+
return;
|
|
75
|
+
cached.unavailable = { ...cached.unavailable, [service]: code };
|
|
76
|
+
writeJson(dir, 'account.json', cached);
|
|
77
|
+
}
|
|
78
|
+
/** Forget a service's unavailability once a read of it succeeds. */
|
|
79
|
+
export function noteAvailable(dir, service) {
|
|
80
|
+
const cached = readJson(join(dir, 'account.json'));
|
|
81
|
+
if (!cached || !(service in cached.unavailable))
|
|
82
|
+
return;
|
|
83
|
+
const { [service]: _gone, ...rest } = cached.unavailable;
|
|
84
|
+
cached.unavailable = rest;
|
|
85
|
+
writeJson(dir, 'account.json', cached);
|
|
86
|
+
}
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
// Sign-in. With ITURAN_TOKEN (inside Comis, the Gate's placeholder) the token
|
|
2
|
+
// is sent as it is and the identity routes are never called. With a username
|
|
3
|
+
// and password, the token is kept in a private cache file and reused until
|
|
4
|
+
// near its end, then refreshed: Ituran's access protection blocks addresses
|
|
5
|
+
// that sign in again and again, and a command-line tool runs once per command.
|
|
6
|
+
// Identity answers carry tokens, so they are never quoted.
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { chmodSync, closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
|
|
9
|
+
import { homedir } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { AxiError } from './errors.js';
|
|
12
|
+
import { fetchAnswer, timeLeft } from './http.js';
|
|
13
|
+
import { VERSION } from './version.js';
|
|
14
|
+
/** A cached token is replaced this long before it ends. */
|
|
15
|
+
const RENEW_BEFORE_MS = 30 * 60_000;
|
|
16
|
+
const GRANT_TIMEOUT_MS = 30_000;
|
|
17
|
+
/** A lock older than this was left by a process that died. */
|
|
18
|
+
const STALE_LOCK_MS = 30_000;
|
|
19
|
+
const LOCK_POLL_MS = 250;
|
|
20
|
+
export const DEVICE_ID = 'ituran-axi';
|
|
21
|
+
export function tokenDir(settings, user, env) {
|
|
22
|
+
const state = env.XDG_STATE_HOME || join(env.HOME || homedir(), '.local', 'state');
|
|
23
|
+
const key = createHash('sha256')
|
|
24
|
+
.update(`${settings.url}|${user}`)
|
|
25
|
+
.digest('hex')
|
|
26
|
+
.slice(0, 16);
|
|
27
|
+
return join(state, 'ituran-axi', key);
|
|
28
|
+
}
|
|
29
|
+
/** expires_in counts minutes on Ituran (1440 = one day). A JWT's exp wins when present. */
|
|
30
|
+
export function expiresAt(token, expiresIn, nowMs) {
|
|
31
|
+
const parts = token.split('.');
|
|
32
|
+
if (parts.length === 3) {
|
|
33
|
+
try {
|
|
34
|
+
const exp = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')).exp;
|
|
35
|
+
if (typeof exp === 'number')
|
|
36
|
+
return exp * 1000;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
/* opaque after all */
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const minutes = typeof expiresIn === 'number' && expiresIn > 0 ? expiresIn : 60;
|
|
43
|
+
return nowMs + minutes * 60_000;
|
|
44
|
+
}
|
|
45
|
+
class TokenSession {
|
|
46
|
+
token;
|
|
47
|
+
constructor(token) {
|
|
48
|
+
this.token = token;
|
|
49
|
+
}
|
|
50
|
+
async header() {
|
|
51
|
+
return `Bearer ${this.token}`;
|
|
52
|
+
}
|
|
53
|
+
async renew() {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
class PasswordSession {
|
|
58
|
+
dir;
|
|
59
|
+
file;
|
|
60
|
+
lock;
|
|
61
|
+
current = null;
|
|
62
|
+
renewed = false;
|
|
63
|
+
settings;
|
|
64
|
+
auth;
|
|
65
|
+
deps;
|
|
66
|
+
now;
|
|
67
|
+
constructor(settings, auth, deps, env, now) {
|
|
68
|
+
this.settings = settings;
|
|
69
|
+
this.auth = auth;
|
|
70
|
+
this.deps = deps;
|
|
71
|
+
this.now = now;
|
|
72
|
+
this.dir = tokenDir(settings, auth.user, env);
|
|
73
|
+
this.file = join(this.dir, 'token.json');
|
|
74
|
+
this.lock = join(this.dir, 'token.lock');
|
|
75
|
+
}
|
|
76
|
+
fresh(t) {
|
|
77
|
+
return t !== null && t.expires_at - this.now().getTime() > RENEW_BEFORE_MS;
|
|
78
|
+
}
|
|
79
|
+
readCache() {
|
|
80
|
+
try {
|
|
81
|
+
const t = JSON.parse(readFileSync(this.file, 'utf8'));
|
|
82
|
+
return typeof t.access_token === 'string' &&
|
|
83
|
+
typeof t.expires_at === 'number'
|
|
84
|
+
? t
|
|
85
|
+
: null;
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
writeCache(t) {
|
|
92
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
93
|
+
chmodSync(this.dir, 0o700);
|
|
94
|
+
const tmp = `${this.file}.${process.pid}.tmp`;
|
|
95
|
+
writeFileSync(tmp, JSON.stringify(t), { mode: 0o600 });
|
|
96
|
+
renameSync(tmp, this.file);
|
|
97
|
+
}
|
|
98
|
+
async withLock(fn) {
|
|
99
|
+
mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
100
|
+
for (;;) {
|
|
101
|
+
try {
|
|
102
|
+
closeSync(openSync(this.lock, 'wx', 0o600));
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
if (error.code !== 'EEXIST')
|
|
107
|
+
throw error;
|
|
108
|
+
let old = false;
|
|
109
|
+
try {
|
|
110
|
+
old = Date.now() - statSync(this.lock).mtimeMs > STALE_LOCK_MS;
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (old) {
|
|
116
|
+
rmSync(this.lock, { force: true });
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (timeLeft(this.settings, this.now) < LOCK_POLL_MS * 2) {
|
|
120
|
+
throw new AxiError('unreachable', 'Another ituran-axi command is signing in. Run this one again in a moment.');
|
|
121
|
+
}
|
|
122
|
+
await this.deps.sleep(LOCK_POLL_MS);
|
|
123
|
+
// The other command may have finished signing in.
|
|
124
|
+
const done = this.readCache();
|
|
125
|
+
if (this.fresh(done))
|
|
126
|
+
return fn();
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
try {
|
|
130
|
+
return await fn();
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
rmSync(this.lock, { force: true });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async grant(body) {
|
|
137
|
+
const answer = await fetchAnswer(this.deps, new URL(`${this.settings.identity}/oauth/token`), {
|
|
138
|
+
method: 'POST',
|
|
139
|
+
headers: {
|
|
140
|
+
Accept: 'application/json',
|
|
141
|
+
'Content-Type': 'application/json',
|
|
142
|
+
'User-Agent': `ituran-axi/${VERSION}`,
|
|
143
|
+
},
|
|
144
|
+
body: JSON.stringify(body),
|
|
145
|
+
}, Math.min(GRANT_TIMEOUT_MS, timeLeft(this.settings, this.now)));
|
|
146
|
+
if (answer.status === 474) {
|
|
147
|
+
throw new AxiError('access_blocked', "Ituran's access protection blocked this computer's address. Do not retry; ask Ituran to review it.");
|
|
148
|
+
}
|
|
149
|
+
if (answer.status === 400 || answer.status === 401) {
|
|
150
|
+
throw new AxiError('auth_failed', 'Ituran refused the username or password. Check ITURAN_USERNAME and ITURAN_PASSWORD.');
|
|
151
|
+
}
|
|
152
|
+
if (answer.status < 200 || answer.status >= 300) {
|
|
153
|
+
throw new AxiError('ituran_error', `Ituran's sign-in failed with ${answer.status}.`, { status: answer.status });
|
|
154
|
+
}
|
|
155
|
+
const j = (answer.json ?? {});
|
|
156
|
+
if (typeof j.access_token !== 'string' || !j.access_token) {
|
|
157
|
+
throw new AxiError('two_step_required', 'Ituran asked for a second sign-in step, which no unattended tool can complete. Use a service account without two-step sign-in.');
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
access_token: j.access_token,
|
|
161
|
+
...(typeof j.refresh_token === 'string'
|
|
162
|
+
? { refresh_token: j.refresh_token }
|
|
163
|
+
: {}),
|
|
164
|
+
expires_at: expiresAt(j.access_token, j.expires_in, this.now().getTime()),
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
passwordGrant() {
|
|
168
|
+
return this.grant({
|
|
169
|
+
grant_type: 'password',
|
|
170
|
+
username: this.auth.user,
|
|
171
|
+
password: this.auth.password,
|
|
172
|
+
device_id: DEVICE_ID,
|
|
173
|
+
culture: 'en-US',
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
async header() {
|
|
177
|
+
if (this.current && this.fresh(this.current))
|
|
178
|
+
return `Bearer ${this.current.access_token}`;
|
|
179
|
+
const cached = this.readCache();
|
|
180
|
+
if (cached && this.fresh(cached)) {
|
|
181
|
+
this.current = cached;
|
|
182
|
+
return `Bearer ${cached.access_token}`;
|
|
183
|
+
}
|
|
184
|
+
this.current = await this.withLock(async () => {
|
|
185
|
+
const again = this.readCache();
|
|
186
|
+
if (again && this.fresh(again))
|
|
187
|
+
return again;
|
|
188
|
+
let next = null;
|
|
189
|
+
if (again?.refresh_token) {
|
|
190
|
+
try {
|
|
191
|
+
next = await this.grant({
|
|
192
|
+
grant_type: 'refresh_token',
|
|
193
|
+
refresh_token: again.refresh_token,
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
if (!(error instanceof AxiError && error.code === 'auth_failed'))
|
|
198
|
+
throw error;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
next ??= await this.passwordGrant();
|
|
202
|
+
this.writeCache(next);
|
|
203
|
+
return next;
|
|
204
|
+
});
|
|
205
|
+
return `Bearer ${this.current.access_token}`;
|
|
206
|
+
}
|
|
207
|
+
async renew(used) {
|
|
208
|
+
if (this.renewed)
|
|
209
|
+
return false;
|
|
210
|
+
this.renewed = true;
|
|
211
|
+
await this.withLock(async () => {
|
|
212
|
+
const cached = this.readCache();
|
|
213
|
+
if (!cached || `Bearer ${cached.access_token}` === used) {
|
|
214
|
+
rmSync(this.file, { force: true });
|
|
215
|
+
const next = await this.passwordGrant();
|
|
216
|
+
this.writeCache(next);
|
|
217
|
+
this.current = next;
|
|
218
|
+
}
|
|
219
|
+
else {
|
|
220
|
+
this.current = cached;
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
export function sessionFor(settings, deps, env, now) {
|
|
227
|
+
return settings.auth.kind === 'token'
|
|
228
|
+
? new TokenSession(settings.auth.token)
|
|
229
|
+
: new PasswordSession(settings, settings.auth, deps, env, now);
|
|
230
|
+
}
|
|
231
|
+
/** Forget the cached token for these settings. Nothing is sent to Ituran. */
|
|
232
|
+
export function forgetToken(settings, user, env) {
|
|
233
|
+
const file = join(tokenDir(settings, user, env), 'token.json');
|
|
234
|
+
let existed = false;
|
|
235
|
+
try {
|
|
236
|
+
statSync(file);
|
|
237
|
+
existed = true;
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
/* nothing cached */
|
|
241
|
+
}
|
|
242
|
+
rmSync(file, { force: true });
|
|
243
|
+
return existed;
|
|
244
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { main } from '../cli/run.js';
|
|
3
|
+
import { defaultDeps } from '../http.js';
|
|
4
|
+
// A reader that closes early, as in `ituran-axi ... | head`, is a normal end.
|
|
5
|
+
process.stdout.on('error', (error) => {
|
|
6
|
+
if (error.code === 'EPIPE')
|
|
7
|
+
process.exit(0);
|
|
8
|
+
throw error;
|
|
9
|
+
});
|
|
10
|
+
process.exitCode = await main(process.argv.slice(2), {
|
|
11
|
+
stdout: (text) => {
|
|
12
|
+
process.stdout.write(text);
|
|
13
|
+
},
|
|
14
|
+
env: process.env,
|
|
15
|
+
now: () => new Date(),
|
|
16
|
+
http: defaultDeps,
|
|
17
|
+
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Strict parsing with node:util parseArgs, following the Comis AXI fixture:
|
|
2
|
+
// unknown flags, repeated single flags, extra arguments and values on boolean
|
|
3
|
+
// flags are refused. A refusal names the flag, never its value. "--" ends flags.
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { usage } from '../errors.js';
|
|
6
|
+
import { commandName, } from './table.js';
|
|
7
|
+
// An odd flag is not echoed: it may hold a value meant for somewhere else.
|
|
8
|
+
const shownFlag = (raw) => /^--?[A-Za-z0-9][A-Za-z0-9-]{0,40}$/.test(raw) ? ` ${raw}` : '';
|
|
9
|
+
export function parseCommand(spec, argv) {
|
|
10
|
+
const name = commandName(spec);
|
|
11
|
+
const options = {};
|
|
12
|
+
for (const [flag, f] of Object.entries(spec.flags)) {
|
|
13
|
+
options[flag] = f.multiple
|
|
14
|
+
? { type: f.type, multiple: true }
|
|
15
|
+
: { type: f.type };
|
|
16
|
+
}
|
|
17
|
+
const valid = Object.keys(spec.flags).map((f) => `--${f}`);
|
|
18
|
+
let result;
|
|
19
|
+
try {
|
|
20
|
+
result = parseArgs({
|
|
21
|
+
args: argv,
|
|
22
|
+
options,
|
|
23
|
+
strict: false,
|
|
24
|
+
allowPositionals: true,
|
|
25
|
+
tokens: true,
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
throw usage(`Invalid arguments for \`${name}\`.`);
|
|
30
|
+
}
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
for (const token of result.tokens) {
|
|
33
|
+
if (token.kind !== 'option')
|
|
34
|
+
continue;
|
|
35
|
+
const f = spec.flags[token.name];
|
|
36
|
+
if (!f) {
|
|
37
|
+
throw usage(`Unknown flag${shownFlag(token.rawName)} for \`${name}\`. ${valid.length ? `Valid flags: ${valid.join(', ')}.` : 'It takes no flags.'}`);
|
|
38
|
+
}
|
|
39
|
+
if (f.type === 'boolean' && token.inlineValue)
|
|
40
|
+
throw usage(`--${token.name} takes no value.`);
|
|
41
|
+
if (f.type === 'string' &&
|
|
42
|
+
(token.value === undefined || token.value === '')) {
|
|
43
|
+
throw usage(`--${token.name} needs a value: --${token.name} ${f.value ?? '<value>'}.`);
|
|
44
|
+
}
|
|
45
|
+
if (!f.multiple && seen.has(token.name))
|
|
46
|
+
throw usage(`--${token.name} is given more than once.`);
|
|
47
|
+
seen.add(token.name);
|
|
48
|
+
}
|
|
49
|
+
const positionals = result.positionals;
|
|
50
|
+
const required = spec.args.filter((a) => a.required);
|
|
51
|
+
if (positionals.length < required.length) {
|
|
52
|
+
throw usage(`Missing ${required[positionals.length]?.name ?? 'argument'} for \`${name}\`.`);
|
|
53
|
+
}
|
|
54
|
+
const variadic = spec.args.at(-1)?.variadic === true;
|
|
55
|
+
if (!variadic && positionals.length > spec.args.length) {
|
|
56
|
+
throw usage(spec.args.length
|
|
57
|
+
? `\`${name}\` takes ${spec.args.map((a) => a.name).join(' ')}; there is an extra argument.`
|
|
58
|
+
: `\`${name}\` takes no arguments.`);
|
|
59
|
+
}
|
|
60
|
+
const tokens = [];
|
|
61
|
+
for (const token of result.tokens) {
|
|
62
|
+
if (token.kind === 'option') {
|
|
63
|
+
tokens.push({ kind: 'option', name: token.name, value: token.value });
|
|
64
|
+
}
|
|
65
|
+
else if (token.kind === 'positional') {
|
|
66
|
+
tokens.push({ kind: 'positional', value: token.value });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return { values: result.values, positionals, tokens };
|
|
70
|
+
}
|