Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

feat(iot): COGNITUM_SEED_TOKEN bearer auth via .env (1.0.0-alpha.5) (#1684)

rUv8b8127d75e12
diff --git a/v3/@claude-flow/plugin-iot-cognitum/README.md b/v3/@claude-flow/plugin-iot-cognitum/README.md
index 068c965902..3a4bb0c6aa 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/README.md
+++ b/v3/@claude-flow/plugin-iot-cognitum/README.md
@@ -18,6 +18,26 @@ The Seed is an edge appliance with on-device vector store, Ed25519 cryptographic
npx -y -p @claude-flow/plugin-iot-cognitum@latest cognitum-iot --help
```
+## Authentication via `.env`
+
+Create a `.env` file in your project root (or any parent directory):
+
+```bash
+COGNITUM_SEED_TOKEN=your-bearer-token-here
+# Optional overrides:
+COGNITUM_SEED_ENDPOINT=https://169.254.42.1:8443 # default when token is set
+IOT_FLEET_ID=my-fleet
+IOT_ZONE_ID=zone-1
+IOT_TLS_INSECURE=true # accept self-signed cert (default: true)
+```
+
+The bin walks up from CWD looking for `.env`, loads it without overwriting existing process.env vars, then:
+
+- When `COGNITUM_SEED_TOKEN` is present β†’ default endpoint switches to `https://169.254.42.1:8443` (LAN/HTTPS) and the token is passed as the bearer/pairing token on `register`.
+- When no token β†’ default endpoint stays at `http://169.254.42.1` (USB-C link-local, read-only).
+
+Token scope on Seed varies β€” read endpoints work with most tokens; `store/ingest` and some admin operations require a write-scoped token. See https://cognitum.one for token tier documentation.
+
## Commands
| Command | Description |
diff --git a/v3/@claude-flow/plugin-iot-cognitum/__tests__/integration/full-plugin-smoke.mjs b/v3/@claude-flow/plugin-iot-cognitum/__tests__/integration/full-plugin-smoke.mjs
index 3b794c5c4a..0208e0fe25 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/__tests__/integration/full-plugin-smoke.mjs
+++ b/v3/@claude-flow/plugin-iot-cognitum/__tests__/integration/full-plugin-smoke.mjs
@@ -12,8 +12,47 @@
* Run from the plugin directory after `npm run build`.
*/
import { IoTCognitumPlugin } from '../../dist/plugin.js';
+import { readFileSync, existsSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+// Load .env from CWD (or walk up) so COGNITUM_SEED_TOKEN is available.
+function loadDotenv() {
+ let dir = process.cwd();
+ for (let i = 0; i < 8; i++) {
+ const f = resolve(dir, '.env');
+ if (existsSync(f)) {
+ for (const line of readFileSync(f, 'utf8').split('\n')) {
+ const t = line.trim();
+ if (!t || t.startsWith('#')) continue;
+ const eq = t.indexOf('=');
+ if (eq < 1) continue;
+ const k = t.slice(0, eq).trim();
+ let v = t.slice(eq + 1).trim();
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
+ if (process.env[k] === undefined) process.env[k] = v;
+ }
+ return f;
+ }
+ const parent = resolve(dir, '..');
+ if (parent === dir) break;
+ dir = parent;
+ }
+ return null;
+}
+const envFile = loadDotenv();
-const SEED_ENDPOINT = process.env.SEED_ENDPOINT ?? 'http://169.254.42.1';
+const SEED_TOKEN = process.env.COGNITUM_SEED_TOKEN;
+const SEED_ENDPOINT =
+ process.env.SEED_ENDPOINT ?? (SEED_TOKEN ? 'https://169.254.42.1:8443' : 'http://169.254.42.1');
+
+console.log(`[smoke] env: ${envFile ?? '(none)'}`);
+console.log(`[smoke] endpoint: ${SEED_ENDPOINT}`);
+console.log(`[smoke] bearer token: ${SEED_TOKEN ? 'loaded' : 'absent'}`);
+
+// Self-signed cert tolerance for pair-window fetch (https port uses dev cert).
+if (SEED_ENDPOINT.startsWith('https://')) {
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
+}
const plugin = new IoTCognitumPlugin();
const noop = () => undefined;
@@ -66,8 +105,14 @@ const run = async (label, fn) => {
section('iot init');
await run('init', () => cmd('iot init').handler({ _: [], 'fleet-id': 'test-fleet', 'zone-id': 'zone-test' }));
-section('iot register (default endpoint)');
-await run('register', () => cmd('iot register').handler({ _: [], endpoint: SEED_ENDPOINT }));
+section(`iot register (${SEED_ENDPOINT}${SEED_TOKEN ? ' + bearer' : ''})`);
+await run('register', () =>
+ cmd('iot register').handler({
+ _: [],
+ endpoint: SEED_ENDPOINT,
+ ...(SEED_TOKEN ? { token: SEED_TOKEN } : {}),
+ }),
+);
const coord = plugin['coordinator'];
const devices = coord ? coord.listDevices() : [];
@@ -120,14 +165,23 @@ await run('query (k=3)', () =>
);
section(`iot ingest ${deviceId} (1 tagged test vector)`);
-await run('ingest 1 vector', () =>
- cmd('iot ingest').handler(
- dArgs({
- vector: '[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]',
- metadata: JSON.stringify({ tag: 'smoke-test', ts: new Date().toISOString() }),
- }),
- ),
-);
+await run('ingest 1 vector (requires write-scoped token)', async () => {
+ try {
+ await cmd('iot ingest').handler(
+ dArgs({
+ vector: '[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]',
+ metadata: JSON.stringify({ tag: 'smoke-test', ts: new Date().toISOString() }),
+ }),
+ );
+ } catch (err) {
+ const msg = err?.message ?? String(err);
+ if (/not authorized|forbidden|401|403/i.test(msg)) {
+ console.log(`[expected] token lacks ingest scope: ${msg}`);
+ return;
+ }
+ throw err;
+ }
+});
// ============================================================
// Tier 4: pair / unpair round-trip with unique client-name
@@ -139,9 +193,23 @@ const pairClient = `smoke-test-${Date.now()}`;
section('open pair window (direct API)');
await run('open pair window (90s)', async () => {
+ // Check first β€” avoid 429 if window is already open
+ const statusResp = await fetch(`${SEED_ENDPOINT}/api/v1/pair/status`, {
+ headers: SEED_TOKEN ? { authorization: `Bearer ${SEED_TOKEN}` } : {},
+ });
+ if (statusResp.ok) {
+ const s = await statusResp.json();
+ if (s.pairing_window_open) {
+ console.log(`[ok] window already open (${s.window_remaining_secs}s remaining); skipping reopen`);
+ return;
+ }
+ }
const resp = await fetch(`${SEED_ENDPOINT}/api/v1/pair/window`, {
method: 'POST',
- headers: { 'content-type': 'application/json' },
+ headers: {
+ 'content-type': 'application/json',
+ ...(SEED_TOKEN ? { authorization: `Bearer ${SEED_TOKEN}` } : {}),
+ },
body: JSON.stringify({ duration_secs: 90 }),
});
if (!resp.ok) throw new Error(`open window: HTTP ${resp.status}`);
diff --git a/v3/@claude-flow/plugin-iot-cognitum/package.json b/v3/@claude-flow/plugin-iot-cognitum/package.json
index af3f48076c..d889424df9 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/package.json
+++ b/v3/@claude-flow/plugin-iot-cognitum/package.json
@@ -1,6 +1,6 @@
{
"name": "@claude-flow/plugin-iot-cognitum",
- "version": "1.0.0-alpha.4",
+ "version": "1.0.0-alpha.5",
"description": "IoT Cognitum Seed device-agent bridge β€” treat every Seed as a Ruflo agent. Get a Seed at https://cognitum.one.",
"homepage": "https://cognitum.one",
"type": "module",
diff --git a/v3/@claude-flow/plugin-iot-cognitum/src/bin.ts b/v3/@claude-flow/plugin-iot-cognitum/src/bin.ts
index 6e8c6b20e6..b6334a4994 100644
--- a/v3/@claude-flow/plugin-iot-cognitum/src/bin.ts
+++ b/v3/@claude-flow/plugin-iot-cognitum/src/bin.ts
@@ -3,14 +3,65 @@
* Standalone CLI shim for @claude-flow/plugin-iot-cognitum.
* Maps `cognitum-iot <subcommand> [args]` -> CLICommandDefinition handlers.
*
- * Endpoint default: when --endpoint/-e is omitted on `register`,
- * defaults to http://169.254.42.1 (the Cognitum Seed link-local USB address).
+ * Endpoint defaults:
+ * - http://169.254.42.1 (USB-C link-local, no auth β€” read-only paths)
+ * - https://169.254.42.1:8443 (LAN/HTTPS + bearer β€” full access including writes)
+ *
+ * Auth: COGNITUM_SEED_TOKEN is read from process.env (loaded from .env in CWD
+ * if present) and passed to register as the pairing/bearer token. When set,
+ * the default endpoint switches to the HTTPS LAN address.
*/
+import { readFileSync, existsSync } from 'node:fs';
+import { resolve } from 'node:path';
import { IoTCognitumPlugin } from './plugin.js';
import type { PluginContext } from '@claude-flow/shared/src/plugin-interface.js';
-const SEED_DEFAULT_ENDPOINT = 'http://169.254.42.1';
+const SEED_LINK_LOCAL = 'http://169.254.42.1';
+const SEED_LAN_HTTPS = 'https://169.254.42.1:8443';
+
+/**
+ * Tiny .env loader. Walks up from CWD looking for a .env, reads KEY=VALUE
+ * lines (ignoring blanks and # comments), and applies them to process.env
+ * WITHOUT overwriting variables already set in the real environment.
+ */
+function loadDotenv(): { loaded: string | null; count: number } {
+ let dir = process.cwd();
+ for (let i = 0; i < 8; i++) {
+ const candidate = resolve(dir, '.env');
+ if (existsSync(candidate)) {
+ const text = readFileSync(candidate, 'utf8');
+ let count = 0;
+ for (const rawLine of text.split('\n')) {
+ const line = rawLine.trim();
+ if (!line || line.startsWith('#')) continue;
+ const eq = line.indexOf('=');
+ if (eq < 1) continue;
+ const key = line.slice(0, eq).trim();
+ let val = line.slice(eq + 1).trim();
+ // Strip surrounding quotes
+ if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
+ val = val.slice(1, -1);
+ }
+ if (process.env[key] === undefined) {
+ process.env[key] = val;
+ count++;
+ }
+ }
+ return { loaded: candidate, count };
+ }
+ const parent = resolve(dir, '..');
+ if (parent === dir) break;
+ dir = parent;
+ }
+ return { loaded: null, count: 0 };
+}
+
+loadDotenv();
+
+const SEED_TOKEN = process.env.COGNITUM_SEED_TOKEN;
+const SEED_DEFAULT_ENDPOINT =
+ process.env.COGNITUM_SEED_ENDPOINT ?? (SEED_TOKEN ? SEED_LAN_HTTPS : SEED_LINK_LOCAL);
function makeContext(): PluginContext {
// Minimal in-memory context for standalone CLI use.
@@ -131,7 +182,15 @@ function printHelp(commandNames: string[]): void {
console.log('');
console.log('Usage: cognitum-iot <subcommand> [options]');
console.log('');
- console.log('Default endpoint: ' + SEED_DEFAULT_ENDPOINT + ' (Seed link-local USB address)');
+ console.log('Default endpoint: ' + SEED_DEFAULT_ENDPOINT);
+ console.log(' - http://169.254.42.1 (USB-C link-local, no auth, read-only)');
+ console.log(' - https://169.254.42.1:8443 (LAN/HTTPS, COGNITUM_SEED_TOKEN required, full access)');
+ console.log('');
+ console.log('Auth: set COGNITUM_SEED_TOKEN in .env or environment to use the bearer-protected');
+ console.log(' LAN endpoint and unlock writes (ingest, unpair, etc).');
+ console.log(' Status: ' + (SEED_TOKEN ? 'βœ“ token loaded' : 'βœ— no token (link-local only)'));
+ console.log('');
+ console.log('Hardware: get a Seed at https://cognitum.one');
console.log('');
console.log('Subcommands:');
for (const n of commandNames) {
@@ -171,10 +230,16 @@ async function main(): Promise<void> {
const cmd = commands.find((c) => c.name === resolved.name)!;
const args = aliasShortToLong(parseArgs(resolved.rest));
- // Endpoint default for `iot register`: fall back to Seed link-local address.
- if (resolved.name === 'iot register' && !args['endpoint']) {
- args['endpoint'] = SEED_DEFAULT_ENDPOINT;
- console.error(`[info] No --endpoint supplied; defaulting to ${SEED_DEFAULT_ENDPOINT}`);
+ // Endpoint + token defaults for `iot register`.
+ if (resolved.name === 'iot register') {
+ if (!args['endpoint']) {
+ args['endpoint'] = SEED_DEFAULT_ENDPOINT;
+ console.error(`[info] No --endpoint supplied; defaulting to ${SEED_DEFAULT_ENDPOINT}`);
+ }
+ if (!args['token'] && SEED_TOKEN) {
+ args['token'] = SEED_TOKEN;
+ console.error('[info] Using COGNITUM_SEED_TOKEN from environment');
+ }
}
try {