@bugb-technologies/bravos 1.22.0 → 1.24.0

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/dist/artifacts.js CHANGED
@@ -1,4 +1,4 @@
1
- // @comment -- "Fetches, verifies and stages the two binary bundles bravos owns: the licensed analyzer (bravos-cli and its scanners) and the code graph (codegraph-build, codegraph-mcp). A port of the Python CLI's analyzer.py and artifact.py: each published file has a detached bravos-artifact-signature/1 statement signed under the artifact key (never the licence key), the manifest is verified before it is read, the tarball before it is opened, and the unpack refuses links, absolute paths, '..', duplicates and anything past a size ceiling. Nothing touches the network without a licence the portal accepts: the download URLs come from the account portal, which checks the licence server-side and presigns a short-lived link to the private bucket; BRAVOS_ARTIFACT_BASE_URL points at a plain directory instead, for tests and air-gapped mirrors."
1
+ // @comment -- "Fetches, verifies and stages the binary bundles bravos owns: the licensed analyzer (bravos-cli and its scanners), the code graph (codegraph-build, codegraph-mcp) and the free macOS notifier (Bravos.app). A port of the Python CLI's analyzer.py and artifact.py: each published file has a detached bravos-artifact-signature/1 statement signed under the artifact key (never the licence key), the manifest is verified before it is read, the tarball before it is opened, and the unpack refuses links, absolute paths, '..', duplicates and anything past a size ceiling. Nothing licensed touches the network without a licence the portal accepts (the notifier, on every plan, comes from the public release bucket instead, under the same signature checks): the download URLs come from the account portal, which checks the licence server-side and presigns a short-lived link to the private bucket; BRAVOS_ARTIFACT_BASE_URL points at a plain directory instead, for tests and air-gapped mirrors."
2
2
  import { createHash, createPublicKey, verify as cryptoVerify } from 'node:crypto';
3
3
  import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeSync } from 'node:fs';
4
4
  import { arch, platform } from 'node:os';
@@ -7,14 +7,14 @@ import { gunzipSync } from 'node:zlib';
7
7
  import { refresh, userAgent } from './device.js';
8
8
  import { licenceLib } from './licence.js';
9
9
  import { BravosError } from './types.js';
10
- import { ANALYZER_VERSION, CODEGRAPH_VERSION } from './versions.js';
10
+ import { ANALYZER_VERSION, CODEGRAPH_VERSION, NOTIFIER_VERSION } from './versions.js';
11
11
  export const MAGIC = 'bravos-artifact-signature/1';
12
12
  export const ARTIFACT_KID = 'bugb-artifact-2026a';
13
13
  // @comment -- "The artifact signing key's public half, fixed in the source like the licence key and distinct from it: a licence says who may run the analyzer, a signature says these bytes are the ones Bugb published. No environment variable, flag or file adds a key; tests hand verify() a throwaway set in-process."
14
14
  export const TRUSTED_ARTIFACT_KEYS = Object.freeze({
15
15
  [ARTIFACT_KID]: '-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAX2x2o4eSFTU+Ti1Kkew+/t9LO4POT4D0r9aoRtJbz9o=\n-----END PUBLIC KEY-----\n',
16
16
  });
17
- export const MANIFEST_SCHEMAS = { analyzer: 'bravos-analyzer-manifest/2', codegraph: 'bravos-codegraph-manifest/1' };
17
+ export const MANIFEST_SCHEMAS = { analyzer: 'bravos-analyzer-manifest/2', codegraph: 'bravos-codegraph-manifest/1', notifier: 'bravos-notifier-manifest/1' };
18
18
  export const BUNDLE_FILE = 'BUNDLE.json';
19
19
  const MAX_MANIFEST_BYTES = 256 * 1024;
20
20
  const MAX_SIGNATURE_BYTES = 4096;
@@ -27,12 +27,26 @@ export const TARGETS = ['aarch64-apple-darwin', 'x86_64-apple-darwin', 'x86_64-u
27
27
  export const REQUIRED = {
28
28
  analyzer: ['bravos-cli', BUNDLE_FILE, 'rules/semgrep/PACK.toml', 'rules/sinks.yaml', 'rules/middleware.yaml', 'bin/gitleaks', 'bin/osv-scanner', 'bin/kics', 'bin/zizmor', 'share/kics/assets/queries', 'licences/NOTICE'],
29
29
  codegraph: ['codegraph-build', 'codegraph-mcp', BUNDLE_FILE],
30
+ notifier: ['Bravos.app/Contents/MacOS/Bravos', 'Bravos.app/Contents/Info.plist', BUNDLE_FILE],
30
31
  };
31
32
  export const EXECUTABLES = {
32
33
  analyzer: ['bravos-cli', 'bin/gitleaks', 'bin/osv-scanner', 'bin/kics', 'bin/zizmor'],
33
34
  codegraph: ['codegraph-build', 'codegraph-mcp'],
35
+ notifier: ['Bravos.app/Contents/MacOS/Bravos'],
34
36
  };
35
- export const VERSIONS = { analyzer: ANALYZER_VERSION, codegraph: CODEGRAPH_VERSION };
37
+ export const VERSIONS = { analyzer: ANALYZER_VERSION, codegraph: CODEGRAPH_VERSION, notifier: NOTIFIER_VERSION };
38
+ /** The notifier is one universal (arm64 + x86_64) macOS app, so its manifest names this one target. */
39
+ export const NOTIFIER_TARGET = 'universal-apple-darwin';
40
+ /** The notifier executable inside a staged bundle. */
41
+ export const NOTIFIER_EXECUTABLE = 'Bravos.app/Contents/MacOS/Bravos';
42
+ // @comment -- "Where the notifier is published: the public release bucket (the one that serves the desktop app), under bravos/notifier/<version>/. Desktop notifications are on every plan, so the notifier is fetched without a licence; what makes it safe to run is the artifact signature checked before unpacking, plus Apple's notarization of the app inside."
43
+ export const NOTIFIER_BASE_URL = 'https://pub-e89c47f816b54f5c8e6c54335574be9b.r2.dev/bravos';
44
+ // @comment -- "The build of `kind` this machine runs: the host triple for the analyzer and the code graph, the universal macOS app for the notifier (macOS only), or null when none is published for this platform."
45
+ export function bundleTarget(kind, os = platform()) {
46
+ if (kind === 'notifier')
47
+ return os === 'darwin' ? NOTIFIER_TARGET : null;
48
+ return hostTarget();
49
+ }
36
50
  export function hostTarget() {
37
51
  const p = platform();
38
52
  const a = arch();
@@ -262,7 +276,7 @@ export function staged(env, kind) {
262
276
  return null;
263
277
  }
264
278
  const candidates = [join(home, kind, 'current')];
265
- const t = hostTarget();
279
+ const t = bundleTarget(kind);
266
280
  if (t)
267
281
  candidates.push(join(home, kind, VERSIONS[kind], t));
268
282
  for (const c of candidates) {
@@ -364,7 +378,8 @@ async function get(f, url, limit, what, headers = {}) {
364
378
  // @comment -- "Where the files come from. With BRAVOS_ARTIFACT_BASE_URL, a plain layout <base>/<kind>/<version>/<file> (tests, mirrors). Otherwise the account portal: GET /api/v1/cli/artifacts/<kind>/<version>/<triple> with the licence as the bearer; the portal verifies it (and, for a device or CI licence, that it has not been revoked), counts the pull, and answers presigned URLs into the private bucket. On 401 or 403 a device licence is renewed once and the request repeated once. The licence token goes to the portal origin and nowhere else; the presigned URLs carry their own authorization."
365
379
  async function urlsFor(kind, version, target, io) {
366
380
  const f = io.fetch ?? fetch;
367
- const base = (io.env[BASE_URL_ENV] || '').trim();
381
+ // The notifier comes from the public bucket in the same plain layout, with no licence and no portal.
382
+ const base = (io.env[BASE_URL_ENV] || '').trim() || (kind === 'notifier' ? NOTIFIER_BASE_URL : '');
368
383
  if (base) {
369
384
  const root = `${base.replace(/\/+$/, '')}/${kind}/${version}`;
370
385
  return { manifest: `${root}/manifest.json`, manifestSig: `${root}/manifest.json.sig`, artifact: (file) => `${root}/${file}`, artifactSig: (file) => `${root}/${file}.sig` };
@@ -416,9 +431,9 @@ export async function install(kind, io, opts = {}) {
416
431
  if (io.env[NO_FETCH_ENV])
417
432
  throw new BravosError(`${NO_FETCH_ENV} is set: refusing to download the ${kind} bundle`);
418
433
  const version = opts.version ?? VERSIONS[kind];
419
- const target = opts.target ?? hostTarget();
434
+ const target = opts.target ?? bundleTarget(kind);
420
435
  if (!target)
421
- throw new BravosError(`no ${kind} bundle is published for this platform (${platform()} ${arch()}); the targets are ${TARGETS.join(', ')}`);
436
+ throw new BravosError(kind === 'notifier' ? 'the Bravos notifier is a macOS app; on Linux desktop notifications go through notify-send' : `no ${kind} bundle is published for this platform (${platform()} ${arch()}); the targets are ${TARGETS.join(', ')}`);
422
437
  const f = io.fetch ?? fetch;
423
438
  const keys = io.keys ?? TRUSTED_ARTIFACT_KEYS;
424
439
  const echo = io.echo ?? (() => { });
package/dist/cli.js CHANGED
@@ -28,7 +28,7 @@ import { activate, importLicence } from './account.js';
28
28
  import { listDevices, logout, refresh as refreshDevice, revokeDevice } from './device.js';
29
29
  import * as graph from './codegraph.js';
30
30
  import { askGraph } from './watch.js';
31
- import { plan as setupPlan, runSast, runSetup } from './setup.js';
31
+ import { notifyWanted, plan as setupPlan, runSast, runSetup } from './setup.js';
32
32
  import { isTerminal, setupRoute } from './setup-route.js';
33
33
  import { leaveHandoff } from './prefs.js';
34
34
  import { openInBrowser } from './open.js';
@@ -745,6 +745,11 @@ export function buildProgram(io, result) {
745
745
  for (const b of u.bundles) {
746
746
  lines.push(...(await runSetup(io.env, { [b.id]: true, dryRun }, { echo: io.stdout })));
747
747
  }
748
+ // @comment -- "The notifier is the one bundle upkeep may fetch when it is absent: the person's own notify answer (bravos prefs set notify on) is the go-ahead, it is on every plan, and it only replaces how a notification they asked for is shown. A failure is a line; cards fall back to osascript."
749
+ if (process.platform === 'darwin' && (await notifyWanted(root, io.env))) {
750
+ const n = await runSetup(io.env, { notifier: true, notify: true, dryRun }, { echo: io.stdout }).catch((e) => [`notifier: ${e.message.split('\n')[0]}`]);
751
+ lines.push(...n.filter((l) => !l.startsWith('notifier: already staged')));
752
+ }
748
753
  // Absent pieces are named, never fetched here: a first install is a person's go-ahead.
749
754
  const plan = await setupPlan(io.env);
750
755
  for (const item of plan.items) {
@@ -759,17 +764,18 @@ export function buildProgram(io, result) {
759
764
  }
760
765
  };
761
766
  // @comment -- "bravos setup: the one command. It looks at what was typed and whether there is a terminal (src/setup-route.ts) and does one job: the read-only check, the machine part, the user-level install, the repository part by flags, an unattended first setup, the guided wizard, or upkeep. It is declared after the wizard and repository actions it dispatches to."
762
- const SETUP_FLAGS = 'bravos setup: --tools, --analyzer and --codegraph set up this machine; the other flags set up a repository. Run them as two commands, for example: bravos setup --tools -y, then bravos setup --agent claude';
767
+ const SETUP_FLAGS = 'bravos setup: --tools, --analyzer, --codegraph and --notifier set up this machine; the other flags set up a repository. Run them as two commands, for example: bravos setup --tools -y, then bravos setup --agent claude';
763
768
  repositoryOptions(setupCommand
764
- .description('Set Bravos up, here and on this machine, doing only what is missing. In a terminal it is a guided setup: sign in, install the tools, then this repository\'s agents, PR checks and testing permission; in a repository that already has Bravos it only brings this machine and the repository up to date (--change re-asks the repository\'s choices). Without a terminal (an agent, a script) a plain bravos setup only brings what is already installed up to date. Flags do one part by hand: --tools, --analyzer, --codegraph for this machine; --agent, --autopilot, --ci and the rest for the repository; --yes for an unattended first setup; --check to look and change nothing.')
769
+ .description('Set Bravos up, here and on this machine, doing only what is missing. In a terminal it is a guided setup: sign in, install the tools, then this repository\'s agents, PR checks and testing permission; in a repository that already has Bravos it only brings this machine and the repository up to date (--change re-asks the repository\'s choices). Without a terminal (an agent, a script) a plain bravos setup only brings what is already installed up to date. Flags do one part by hand: --tools, --analyzer, --codegraph, --notifier for this machine; --agent, --autopilot, --ci and the rest for the repository; --yes for an unattended first setup; --check to look and change nothing.')
765
770
  .option('--change', 'ask this repository\'s questions again, with the recorded answers selected')
766
771
  .addOption(new Option('--again', 'the earlier name of --change').hideHelp())
767
772
  .addOption(new Option('--preset <name>', 'starting point for the guided setup').choices(['annotate', 'pr', 'everything']))
768
773
  .option('--analyzer', 'this machine: only the analyzer bundle')
769
774
  .option('--codegraph', 'this machine: only the code graph bundle')
775
+ .option('--notifier', 'this machine (macOS): only the Bravos notifier app, when desktop notifications are on (bravos prefs set notify on)')
770
776
  .option('--tools', 'this machine: guardlink (npm) and cxg (cargo); needs -y')
771
777
  .option('--check', 'report what is here and what setup would do; changes nothing')
772
- .option('-y, --yes', 'alone: no questions, set this repository up with the defaults (or join it). With --tools, --analyzer or --codegraph: run the installers, and fetch a staged bundle again')
778
+ .option('-y, --yes', 'alone: no questions, set this repository up with the defaults (or join it). With --tools, --analyzer, --codegraph or --notifier: run the installers, and fetch a staged bundle again')
773
779
  .option('--json', 'with --check: print the plan as JSON (bravos.setup-plan/v1)'), { guardlink: true });
774
780
  setupCommand.action((dir, opts) => guardedAsync(async (lines) => {
775
781
  const given = new Set(Object.keys(opts).filter((k) => setupCommand.getOptionValueSource(k) === 'cli'));
@@ -782,13 +788,15 @@ export function buildProgram(io, result) {
782
788
  throw new BravosError('bravos setup asks questions here, so it needs a terminal. Without one: bravos setup --yes [--preset pr] [dir]');
783
789
  if (route === 'check' || route === 'machine') {
784
790
  if (dir)
785
- throw new BravosError(`bravos setup ${route === 'check' ? '--check' : '--tools, --analyzer and --codegraph'} is about this machine and takes no folder`);
791
+ throw new BravosError(`bravos setup ${route === 'check' ? '--check' : '--tools, --analyzer, --codegraph and --notifier'} is about this machine and takes no folder`);
786
792
  if (route === 'check' && opts.json) {
787
793
  const p = await setupPlan(io.env);
788
794
  lines.push(JSON.stringify({ schema: 'bravos.setup-plan/v1', plan: p.licence.licensed ? 'licensed' : p.licence.state, items: p.items }, null, 2));
789
795
  return;
790
796
  }
791
- lines.push(...(await runSetup(io.env, { analyzer: opts.analyzer, codegraph: opts.codegraph, tools: opts.tools, check: opts.check, dryRun: opts.dryRun, yes: opts.yes }, { echo: io.stdout })));
797
+ // Whether notifications are on is read from the repository the command runs in: prefs are per clone.
798
+ const notify = await notifyWanted(process.cwd(), io.env);
799
+ lines.push(...(await runSetup(io.env, { analyzer: opts.analyzer, codegraph: opts.codegraph, notifier: opts.notifier, tools: opts.tools, check: opts.check, dryRun: opts.dryRun, yes: opts.yes, notify }, { echo: io.stdout })));
792
800
  return;
793
801
  }
794
802
  if (route === 'upkeep') {
package/dist/guide.js CHANGED
@@ -120,7 +120,7 @@ export const GUIDE_TOPICS = [
120
120
  { name: 'See which design rules hold', skills: ['bravos', 'bravos-recheck'], body: ['bravos rules lists every rule your design states (INV-n in the intent) with its status: broken (a test got through), retest due (the code under it changed since it was tested), unguarded (it can break somewhere and nothing stops it), guarded but untested, not placed (no code is tied to it yet), or holds (a test tried and was refused everywhere it is enforced). Each line names the document the rule came from and the places it is enforced. bravos dashboard shows the same under Threat model, as Design rules in GuardLink\'s sidebar beside Exposures, worst first. Free, read-only, no model; --json prints bravos.rules/v1. On the Team plan the pre-PR check and the PR workflow hold a pull request that changes a file a holding rule is enforced in (the check, or the role table that grants the permission) after that rule was last tested, until its test is replayed or the PR body names the rule; the after-edit note says the same while you work.'] },
121
121
  { name: 'The intake asks, it never blocks', skills: ['bravos-context', 'bravos-annotate'], body: ['Annotation starts in the first session. With no confirmed intent, the agent drafts what the product is for from the README, docs and code (.guardlink/intent.md, every item marked draft), annotates against that draft, and opens the intake page without waiting. Each session asks once for a person to confirm it (bravos review intent, a few minutes) until someone confirms or declines; the agent never confirms for you. Rules drafted from the design are tested and can block a pull request right away; bravos rules and the block message label them draft until a person confirms them. When the answers arrive, the agent re-judges what they changed: an item you mark intended by design is annotated as intended, not as a finding. The intake page brings back the answers each person gave when they reopen it, and saves them as they go; only Confirm makes them count, and it records who and when. Design documents (a PRD, a design document, an earlier threat model) can be added on the page itself: Markdown and text are stored with the usual checks, and a PDF, Word file, slides or link waits for the agent to convert. Every rule cites the section of the document it came from, the page shows that passage under the question, and bravos context check refuses a section the document does not have. The intake and the documents are committed so the team gets them on their next pull; bravos doctor warns when a .gitignore rule keeps them on one machine, and bravos context share --yes narrows a blanket .bravos/ rule. A team that chooses to go without records that under a name, bravos context decline --by "<name>", which is committed like the intent and ends the asking; a coding agent is told never to decline for you. bravos context gate says which state a repository is in.'] },
122
122
  { name: 'Updates', skills: ['bravos'], body: ['Bravos tells you when it is updated. At most once a day a session start asks the npm registry, in a background process the session never waits on, for the latest published version: the same request npm install makes, with only the package name. A newer version shows in the banner and the briefing, and the coach tells a session that is already running, once. Installing it is yours to do (npm install -g @bugb-technologies/bravos); once it is installed the coach has the agent run bravos setup in the repository, which brings its Bravos files up to date. bravos doctor shows the last check. BRAVOS_UPDATE_CHECK=off stops the check, and it never runs in CI.'] },
123
- { name: 'Threat cards', skills: ['bravos-prove', 'bravos-env'], body: ['When an edit adds a critical or high threat to the threat model (an @exposes claim) that no test has confirmed or refuted, a hook that runs after the edit shows you a card in the terminal straight away: the severity, what the threat is, the claim and where it is, its state, and one next step (bravos-env to set up a test target, where you type the authorization, then bravos-prove). The agent is told to raise it in the same reply and recommend confirming it; it never confirms, refutes or accepts a threat itself. Only lines that are not in the last commit count, so existing claims never raise a card, and each threat raises one card per clone. The hook reads the edited files, their committed copy and the local ledger; it runs no guardlink, no test and no network. bravos watch lists every card. BRAVOS_THREAT_CARDS=off turns cards off for a run and bravos prefs set cards off --by "<your name>" for the clone; bravos prefs set notify on --by "<your name>" adds a desktop notification (macOS and Linux).'] },
123
+ { name: 'Threat cards', skills: ['bravos-prove', 'bravos-env'], body: ['When an edit adds a critical or high threat to the threat model (an @exposes claim) that no test has confirmed or refuted, a hook that runs after the edit shows you a card in the terminal straight away: the severity, what the threat is, the claim and where it is, its state, and one next step (bravos-env to set up a test target, where you type the authorization, then bravos-prove). The agent is told to raise it in the same reply and recommend confirming it; it never confirms, refutes or accepts a threat itself. Only lines that are not in the last commit count, so existing claims never raise a card, and each threat raises one card per clone. The hook reads the edited files, their committed copy and the local ledger; it runs no guardlink, no test and no network. bravos watch lists every card. BRAVOS_THREAT_CARDS=off turns cards off for a run and bravos prefs set cards off --by "<your name>" for the clone; bravos prefs set notify on --by "<your name>" adds a desktop notification (macOS and Linux). On macOS, bravos setup --notifier then installs the small Bravos notifier app (signed and notarized by Bugb), so the notification shows as Bravos with its icon and a click opens the dashboard; until it is installed, notifications come through osascript and show as Script Editor.'] },
124
124
  { name: 'The coach', skills: ['bravos'], body: ['Bravos does not wait to be asked. Before each prompt a fast hook (it runs no guardlink and no network) may add one line for the agent. A question about issues, threats, vulnerabilities, findings or risks builds the dashboard while the agent answers, and opens it in your browser the first time in a session; later questions rebuild it and give the path. From the second prompt on it reminds, each topic once a session and at most one per prompt: claims waiting to be confirmed, with the next step (bravos-env to set up a target, where you type the authorization, then bravos-prove); how much of the code the threat model covers, with the next round; and a dashboard that is older than the model. Skills end every round the same way. bravos watch lists each reminder. BRAVOS_COACH=off turns it off for one run, and bravos prefs set coach off --by "<your name>" for this clone.'] },
125
125
  { name: 'Background annotation', skills: ['bravos-annotate'], body: ['While coverage is under 100%, each new session asks the agent to start one annotation pass in a background subagent (one slice at the default budget) beside whatever you asked, and to tell you in one line. It writes annotations only, never code; it commits only as your commits answer allows (bravos prefs set commits), and otherwise leaves its files for you; it reports the files it covered and the coverage change in one line. It does not run again on resume or compact, nor in CI, where the nightly annotates. bravos prefs set annotate off --by "<your name>" switches it off for this clone (background turns it back on), and BRAVOS_AUTO_ANNOTATE=off for one run. In a harness without subagents the agent offers the pass instead.'] },
126
126
  { name: 'Threat-model someone else\'s project', skills: ['bravos-context', 'bravos-annotate'], body: ['bravos-context assumes you are researching software you do not own (an open-source project, a vendor\'s code): it drafts the intent from upstream\'s own docs with links and asks only the scope decisions — which configuration to rate against (shipped defaults or the hardened setup upstream recommends), single organisation or multi-tenant, which attackers are in scope, and the intended-looking behaviours upstream does not document. intent.md records them as Assumptions, and severities are rated against them. Say "this is our product" for the owner interview instead.'] },
package/dist/prefs.js CHANGED
@@ -75,7 +75,11 @@ export async function setPref(root, key, value, by, env, now = new Date()) {
75
75
  throw new BravosError(e instanceof Error ? e.message : String(e));
76
76
  }
77
77
  const what = key === 'commits' ? WHAT[value] : key === 'coach' ? COACH_WHAT[value] : key === 'cards' ? CARDS_WHAT[value] : key === 'notify' ? NOTIFY_WHAT[value] : ANNOTATE_WHAT[value];
78
- return [`${key}: ${value} — from now on the agent will ${what}`, `recorded in ${file} (this clone only; never committed)`];
78
+ const lines = [`${key}: ${value} — from now on the agent will ${what}`, `recorded in ${file} (this clone only; never committed)`];
79
+ // On macOS the notifications come through osascript (shown as Script Editor) until the Bravos notifier app is staged.
80
+ if (key === 'notify' && value === 'on' && process.platform === 'darwin')
81
+ lines.push('on macOS, bravos setup --notifier installs the Bravos notifier app so these show as Bravos (until then they come through osascript, shown as Script Editor)');
82
+ return lines;
79
83
  }
80
84
  // @comment -- "Leaves the hand-off marker after a first install, from the install pipeline itself (which is synchronous, so it cannot load the hook library): the same file and shape hooks/lib/prefs.mjs writeHandoff writes and readHandoff reads, under the clone's git directory. It is what makes the next agent session begin the context step by itself, whichever way Bravos was installed: the guided setup, flags from a script, or the website's setup skill. Returns whether it was written; a folder that is not a git repository, or git not answering, only means the person types the first command."
81
85
  // @mitigates #person-prefs against #governance-forgery using #prefs-outside-tree -- "The marker is written under the git directory, where no commit, clone or pull can put one."
@@ -1,6 +1,6 @@
1
1
  // @comment -- "bravos setup is the one command for setting Bravos up: this decides, from the flags a person actually typed and whether there is a terminal, which of its jobs to do. It is a pure function so the whole table can be tested. First match wins: a read-only check; a refusal when machine and repository flags are mixed; the machine part (bundles, tools); the user-level install; the repository part by flags; an unattended first setup; the guided wizard; and otherwise safe upkeep, which is what an agent or a script with no terminal gets. The two meanings -y had on two commands are kept apart here: with a machine flag it means 'run the installers', alone it means 'no questions, take the defaults', and that second route never runs third-party installers."
2
2
  /** Flags that say "set up this machine": Bravos's own bundles and the third-party tools. */
3
- export const MACHINE_FLAGS = ['tools', 'analyzer', 'codegraph'];
3
+ export const MACHINE_FLAGS = ['tools', 'analyzer', 'codegraph', 'notifier'];
4
4
  /** Flags that only mean something for a repository, so giving one says "set up (or re-apply to) this repository". */
5
5
  export const REPOSITORY_FLAGS = ['agent', 'autopilot', 'prePrHook', 'ci', 'workflows', 'schedule', 'scope', 'linkSkills', 'force', 'guardlinkMode', 'guardlinkInit'];
6
6
  // @comment -- "`given` holds the option names typed on the command line (commander's value source 'cli'), never defaults: --no-guardlink-init defaults to true, so truthiness would read it as given every time."
package/dist/setup.js CHANGED
@@ -3,7 +3,7 @@ import { checkProofTool, formatProofTool } from './proof-tools.js';
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
5
5
  import { isAbsolute, join } from 'node:path';
6
- import { bundleEnvironment, hostTarget, install, missingPaths, olderThan, staged, stagedVersion, VERSIONS } from './artifacts.js';
6
+ import { bundleEnvironment, hostTarget, install, missingPaths, NOTIFIER_EXECUTABLE, olderThan, staged, stagedVersion, VERSIONS } from './artifacts.js';
7
7
  import { graphBin, graphEnv, graphStore } from './codegraph.js';
8
8
  import { whichBin } from './guardlink.js';
9
9
  import { findAnalyzer } from './graphbin.js';
@@ -55,9 +55,11 @@ export async function runSetup(env, opts, io) {
55
55
  for (const item of items)
56
56
  if (item.proofTool)
57
57
  lines.push(formatProofTool(item.proofTool));
58
+ lines.push(...notifierCheck(env, opts, io));
58
59
  return lines;
59
60
  }
60
- const pick = opts.analyzer || opts.codegraph || opts.tools ? { analyzer: !!opts.analyzer, codegraph: !!opts.codegraph, tools: !!opts.tools } : { analyzer: true, codegraph: true, tools: false };
61
+ const narrowed = opts.analyzer || opts.codegraph || opts.tools || opts.notifier;
62
+ const pick = narrowed ? { analyzer: !!opts.analyzer, codegraph: !!opts.codegraph, tools: !!opts.tools, notifier: !!opts.notifier } : { analyzer: true, codegraph: true, tools: false, notifier: true };
61
63
  const bundles = [...(pick.codegraph ? ['codegraph'] : []), ...(pick.analyzer ? ['analyzer'] : [])];
62
64
  for (const kind of bundles) {
63
65
  const what = `bravos setup --${kind}`;
@@ -92,6 +94,8 @@ export async function runSetup(env, opts, io) {
92
94
  lines.push(`${kind}: ${r.version} staged at ${r.dir}${missing.length ? ` — missing ${missing.join(', ')}` : ''}`);
93
95
  lines.push(...selfTest(kind, r.dir, env));
94
96
  }
97
+ if (pick.notifier)
98
+ lines.push(...(await setupNotifier(env, opts, io)));
95
99
  if (pick.tools) {
96
100
  for (const i of items) {
97
101
  if (i.id !== 'guardlink' && i.id !== 'cxg')
@@ -127,6 +131,57 @@ export async function runSetup(env, opts, io) {
127
131
  }
128
132
  return lines;
129
133
  }
134
+ const NOTIFY_OFF = 'desktop notifications are off for this repository (bravos prefs set notify on --by "<your name>" turns them on)';
135
+ // @comment -- "Whether the person asked for desktop notifications in this repository: their recorded notify answer (prefs.json under the git directory), or BRAVOS_NOTIFY=on for this shell. Read-only; a folder that is not a repository reads as off."
136
+ export async function notifyWanted(root, env) {
137
+ if (env.BRAVOS_NOTIFY === 'on')
138
+ return true;
139
+ try {
140
+ const { prefsLib } = await import('./prefs.js');
141
+ const L = await prefsLib();
142
+ return L.readPrefs(L.gitCommonDir(root, env)).notify?.value === 'on';
143
+ }
144
+ catch {
145
+ return false;
146
+ }
147
+ }
148
+ /** bravos setup --check's line for the notifier: macOS only, and only worth a line where notifications are on or it is already staged. */
149
+ export function notifierCheck(env, opts, io = {}) {
150
+ if ((io.platform ?? process.platform) !== 'darwin')
151
+ return [];
152
+ const have = staged(env, 'notifier');
153
+ if (have)
154
+ return [`✔ ${'notifier'.padEnd(10)} ${have}${behindPin(env, 'notifier') ? ` (this bravos pins ${VERSIONS.notifier}: bravos setup --notifier fetches it)` : ''}`];
155
+ return [`✘ ${'notifier'.padEnd(10)} absent — ${opts.notify ? 'bravos setup --notifier fetches the Bravos notifier app' : `only needed with desktop notifications on; ${NOTIFY_OFF}`}`];
156
+ }
157
+ // @comment -- "The notifier step: on macOS, when the person turned desktop notifications on, fetch, verify and stage the Bravos notifier app (Bravos.app) under $BRAVOS_HOME/notifier/, so threat-card notifications show as Bravos instead of Script Editor. It is on every plan, so no licence is asked for. With notifications off nothing is fetched. Asked for by name (--notifier), a failure is an error; as part of a wider setup or upkeep it is a line, because cards fall back to osascript without it."
158
+ // @mitigates #notifier against #tampered-bundle using #artifact-signature -- "setupNotifier() installs only through install(), which verifies the manifest and the tarball against the committed artifact key before anything is unpacked"
159
+ export async function setupNotifier(env, opts, io) {
160
+ if ((io.platform ?? process.platform) !== 'darwin')
161
+ return opts.notifier ? ['notifier: the Bravos notifier is a macOS app; on Linux desktop notifications go through notify-send'] : [];
162
+ if (!opts.notify)
163
+ return opts.notifier ? [`notifier: not installed — ${NOTIFY_OFF}; then run bravos setup --notifier`] : [];
164
+ const have = staged(env, 'notifier');
165
+ const older = behindPin(env, 'notifier');
166
+ if (have && !opts.yes && !older)
167
+ return [`notifier: already staged at ${have}${opts.notifier ? ` (bravos setup --notifier -y fetches ${VERSIONS.notifier} again)` : ''}`];
168
+ if (opts.dryRun)
169
+ return [`dry-run: would fetch the Bravos notifier ${VERSIONS.notifier} from the public release bucket, verify its signature and stage it under $BRAVOS_HOME/notifier/${older ? ` (replacing ${older})` : ''}`];
170
+ let r;
171
+ try {
172
+ r = await install('notifier', { env, fetch: io.fetch, keys: io.keys, echo: io.echo });
173
+ }
174
+ catch (e) {
175
+ if (opts.notifier && (!older || opts.yes))
176
+ throw e;
177
+ const why = e.message.split('\n')[0].slice(0, 200);
178
+ return [older ? `notifier: ${older} stays staged at ${have}; ${VERSIONS.notifier} could not be fetched (${why}). Run bravos setup again later.` : `notifier: could not be fetched (${why}); notifications keep showing through osascript. Run bravos setup --notifier again later.`];
179
+ }
180
+ const out = [`notifier: ${r.version} staged at ${r.dir}${older ? ` (was ${older})` : ''}; threat-card notifications now show as Bravos`];
181
+ const v = spawnSync(join(r.dir, NOTIFIER_EXECUTABLE), ['--version'], { encoding: 'utf8', timeout: 10000, stdio: ['ignore', 'pipe', 'pipe'] });
182
+ out.push(v.status === 0 ? ` ✔ Bravos.app ${(v.stdout || '').trim().split('\n')[0].slice(0, 80)}` : ` ✘ Bravos.app did not run: ${(v.stderr || v.error?.message || '').trim().split('\n')[0]}`);
183
+ return out;
184
+ }
130
185
  // @comment -- "A staged bundle proves it runs: codegraph-build --version, bravos-cli --version, codegraph-mcp --help (it has no --version and answers with its usage), each under the bundle's own environment. A bundle that verifies but does not run is reported, not hidden."
131
186
  export function selfTest(kind, dir, env) {
132
187
  const out = [];
package/dist/versions.js CHANGED
@@ -6,4 +6,7 @@ import { hooksDir } from './paths.js';
6
6
  export const ANALYZER_VERSION = '0.6.2';
7
7
  /** The code graph binaries (codegraph-build, codegraph-mcp), published by specter-v1's codegraph-release workflow. */
8
8
  export const CODEGRAPH_VERSION = '0.1.1';
9
+ // @comment -- "The Bravos notifier app (macOS), built from notifier/macos/ in this repository and released from Bugb-Technologies/specter-v1 (packaging/notifier, .github/workflows/notifier-release.yml), which vendors these sources; must equal notifier/macos/VERSION and specter-v1's packaging/notifier/VERSION."
10
+ /** The macOS notifier app that threat cards post desktop notifications through, installed by bravos setup when notify is on. */
11
+ export const NOTIFIER_VERSION = '1.0.0';
9
12
  export const PROOF_TOOL_PINS = JSON.parse(readFileSync(join(hooksDir(), 'lib', 'proof-tool-pins.json'), 'utf8'));
package/docs/GUIDE.md CHANGED
@@ -138,7 +138,7 @@ Bravos tells you when it is updated. At most once a day a session start asks the
138
138
 
139
139
  Skills: `/bravos-prove` · `/bravos-env`
140
140
 
141
- When an edit adds a critical or high threat to the threat model (an @exposes claim) that no test has confirmed or refuted, a hook that runs after the edit shows you a card in the terminal straight away: the severity, what the threat is, the claim and where it is, its state, and one next step (bravos-env to set up a test target, where you type the authorization, then bravos-prove). The agent is told to raise it in the same reply and recommend confirming it; it never confirms, refutes or accepts a threat itself. Only lines that are not in the last commit count, so existing claims never raise a card, and each threat raises one card per clone. The hook reads the edited files, their committed copy and the local ledger; it runs no guardlink, no test and no network. bravos watch lists every card. BRAVOS_THREAT_CARDS=off turns cards off for a run and bravos prefs set cards off --by "<your name>" for the clone; bravos prefs set notify on --by "<your name>" adds a desktop notification (macOS and Linux).
141
+ When an edit adds a critical or high threat to the threat model (an @exposes claim) that no test has confirmed or refuted, a hook that runs after the edit shows you a card in the terminal straight away: the severity, what the threat is, the claim and where it is, its state, and one next step (bravos-env to set up a test target, where you type the authorization, then bravos-prove). The agent is told to raise it in the same reply and recommend confirming it; it never confirms, refutes or accepts a threat itself. Only lines that are not in the last commit count, so existing claims never raise a card, and each threat raises one card per clone. The hook reads the edited files, their committed copy and the local ledger; it runs no guardlink, no test and no network. bravos watch lists every card. BRAVOS_THREAT_CARDS=off turns cards off for a run and bravos prefs set cards off --by "<your name>" for the clone; bravos prefs set notify on --by "<your name>" adds a desktop notification (macOS and Linux). On macOS, bravos setup --notifier then installs the small Bravos notifier app (signed and notarized by Bugb), so the notification shows as Bravos with its icon and a click opens the dashboard; until it is installed, notifications come through osascript and show as Script Editor.
142
142
 
143
143
  ### The coach
144
144
 
package/docs/UPGRADING.md CHANGED
@@ -2,6 +2,23 @@
2
2
 
3
3
  After `npm install -g @bugb-technologies/bravos`, run **`bravos setup`** in a repository you work in: it brings this machine and that repository up to date. In repositories you work in with an agent you can skip even that: the agent runs it at the start of a session. From 1.12 on you do not have to watch for releases: Bravos tells you when a newer version is out, and after you install it the agent brings each repository up to date. The notes below say what else changes, newest first. (Before 1.9 the same was `bravos setup --tools -y` per machine and `bravos sync` per repository; both still work.)
4
4
 
5
+ ## 1.24.0
6
+
7
+ - **Threat-card notifications on macOS show as Bravos.** They used to come from `osascript` and show as "Script Editor". Bravos now installs a small app signed and notarized by Bugb, `Bravos.app`, under `~/.bravos/notifier/`, and posts them through it, with the Bravos name and icon.
8
+ - **Who gets it:** Macs with desktop notifications turned on (`bravos prefs set notify on`; off by default). The next `bravos setup` installs it, and so does the one the agent runs at the start of a session. `bravos setup --notifier` installs it on its own.
9
+ - **Before it is installed, or if the download fails,** notifications keep going through `osascript` as before, and setup says why.
10
+ - **Linux** is unchanged and still uses `notify-send`.
11
+ - Nothing else changes. Run `bravos setup` in each repository to refresh its installed hook copy.
12
+
13
+ ## 1.23.0
14
+
15
+ - **A team trial licence finds out when the trial has ended.** A team's trial is one licence for the whole account and is never renewed, so until now it kept the Team features working offline until its own date, even after the team bought a plan or the trial was ended early.
16
+ - **What happens now:** at the start of a session, at most every 6 hours, a machine holding a trial licence asks the account portal whether the trial still runs (`POST /api/v1/cli/licence/trial`, with the trial licence as the bearer).
17
+ - **When the trial has ended:** the trial licence is removed from that machine and the next briefing says why. If the team is on a plan now, it says to run `bravos account activate` to sign the machine in with your own licence; otherwise it links to the plans.
18
+ - **When the portal can't be reached,** or answers anything unexpected, the licence is kept.
19
+ - **Never checked:** a paid licence, a licence set through `BRAVOS_LICENCE`, or a machine with `BRAVOS_NO_FETCH` set.
20
+ - Nothing else changes. Run `bravos setup` in each repository to refresh its installed hook copy.
21
+
5
22
  ## 1.22.0
6
23
 
7
24
  - **The intake picks up where you left off.** `bravos review intent` brings back the answers you gave when you reopen it, saves them as you go (only Confirm makes them count), and reuses the page already open instead of opening a second one. After Confirm the page stays open and says who confirmed and when.
package/hooks/cards.mjs CHANGED
@@ -79,7 +79,7 @@ async function main() {
79
79
  const text = ['bravos · threat card', ...shown.map((c) => renderCard(c, { target, harness })), ...(more > 0 ? [`… and ${more} more: bravos watch lists them`] : []), 'Shown once per threat. bravos watch and the dashboard keep the list.'].join('\n');
80
80
  out = { systemMessage: text, hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: [agentLine(cards, { target, harness }), note].filter(Boolean).join('\n') } };
81
81
  for (const c of cards) logWatchEvent(root, { summary: `card: ${c.severity.toUpperCase()} ${c.threat} on ${c.asset} · ${c.file}${c.line ? `:${c.line}` : ''} · untested`, keys: [`bravos-card:${c.threat}`] });
82
- if (prefs.notify?.value === 'on' || process.env.BRAVOS_NOTIFY === 'on') notify(cards[0], basename(root));
82
+ if (prefs.notify?.value === 'on' || process.env.BRAVOS_NOTIFY === 'on') notify(cards[0], basename(root), { root });
83
83
  }
84
84
  } catch (e) {
85
85
  // Cards switched off still leave the principles note; anything else that failed shows nothing.
@@ -1,7 +1,8 @@
1
1
  // @comment -- "Threat cards: right after an edit, a new critical or high @exposes claim that no test has confirmed or refuted is shown to the developer as a card in their terminal (the hook's systemMessage), and the agent is told to raise it and recommend confirming it. Only lines that are not in the last commit count, so existing claims never raise a card; each threat raises one card per clone (recorded under the git directory). Reads files, git's HEAD copy and the local ledger; never runs guardlink, never runs a test and never contacts the network. Dependency-free."
2
- import { spawnSync } from 'node:child_process';
3
- import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs';
4
4
  import { isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
5
6
  import { readProving } from './proving.mjs';
6
7
 
7
8
  export const CARDS_SCHEMA = 'bravos.cards/v1';
@@ -174,20 +175,51 @@ export function decideCards({ root, toolName = '', toolInput = {}, seen = {}, no
174
175
  return { cards, seen: next };
175
176
  }
176
177
 
177
- // @comment -- "An opt-in desktop notification (bravos prefs set notify on): macOS through osascript and Linux through notify-send, with the text passed as arguments to a fixed script, never spliced into it, and nothing waited on."
178
- // @mitigates #threat-cards against #notification-script-injection using #argv-only -- "notify() passes the title and text as osascript and notify-send arguments to a fixed program, so annotation text is never parsed as AppleScript or options"
179
- export function notify(card, repo) {
178
+ // @comment -- "The Bravos notifier app bravos setup stages on macOS when notifications are on ($BRAVOS_HOME/notifier/current/Bravos.app, else ~/.bravos/...): the path of its executable when it is there and executable, else null. Read-only."
179
+ export function notifierApp(env = process.env) {
180
+ const home = env.BRAVOS_HOME || (env.HOME ? join(env.HOME, '.bravos') : null);
181
+ if (!home) return null;
182
+ const exe = join(home, 'notifier', 'current', 'Bravos.app', 'Contents', 'MacOS', 'Bravos');
183
+ try {
184
+ const st = statSync(exe);
185
+ return st.isFile() && st.mode & 0o100 ? exe : null;
186
+ } catch {
187
+ return null;
188
+ }
189
+ }
190
+
191
+ // Started and left: the notifier quits by itself once the notification is posted, and the hook never waits for it.
192
+ function startDetached(cmd, args) {
193
+ const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
194
+ child.on('error', () => {});
195
+ child.unref();
196
+ }
197
+
198
+ // @comment -- "An opt-in desktop notification (bravos prefs set notify on). macOS: the Bravos notifier app when bravos setup staged it, so the notification shows as Bravos with its icon, and a click opens the repository's dashboard when one is built; otherwise osascript (shown as Script Editor). Linux: notify-send. The text is always passed as arguments to a fixed program, never spliced into a script, and nothing is waited on. Returns which way it went (notifier, osascript, notify-send) or null; deps are for tests."
199
+ // @mitigates #threat-cards against #notification-script-injection using #argv-only -- "notify() passes the title and text as arguments to the Bravos notifier, osascript's fixed script or notify-send after --, so annotation text is never parsed as AppleScript or options"
200
+ export function notify(card, repo, { platform = process.platform, env = process.env, root = null, start = startDetached, run = spawnSync } = {}) {
180
201
  const title = `${card.severity === 'critical' ? 'Critical' : 'High'} threat found · ${clean(repo, 40)}`;
181
202
  const text = `${clean(card.file, 80)}${card.line ? `:${card.line}` : ''} · ${clean(card.description, 140) || clean(card.threat, 60)}. Not confirmed yet.`;
182
203
  try {
183
- if (process.platform === 'darwin') {
184
- spawnSync('osascript', ['-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run', title, text], { timeout: 3000, stdio: 'ignore' });
185
- } else if (process.platform === 'linux') {
186
- spawnSync('notify-send', ['--', title, text], { timeout: 3000, stdio: 'ignore' });
204
+ if (platform === 'darwin') {
205
+ const app = notifierApp(env);
206
+ if (app) {
207
+ const dashboard = root ? join(root, '.bravos', 'dashboard', 'index.html') : null;
208
+ const open = dashboard && existsSync(dashboard) ? ['--open', pathToFileURL(dashboard).href] : [];
209
+ start(app, ['--title', title, '--body', text, ...open]);
210
+ return 'notifier';
211
+ }
212
+ run('osascript', ['-e', 'on run argv', '-e', 'display notification (item 2 of argv) with title (item 1 of argv)', '-e', 'end run', title, text], { timeout: 3000, stdio: 'ignore' });
213
+ return 'osascript';
214
+ }
215
+ if (platform === 'linux') {
216
+ run('notify-send', ['--', title, text], { timeout: 3000, stdio: 'ignore' });
217
+ return 'notify-send';
187
218
  }
188
219
  } catch {
189
220
  /* a notification is a convenience */
190
221
  }
222
+ return null;
191
223
  }
192
224
 
193
225
  /** Whether a test target is recorded in the person's proving answer (.guardlink/proving.md), for the next-step wording. */
@@ -1,13 +1,17 @@
1
1
  // @comment -- "Keeps a per-machine (device) licence current: the account portal issues each `bravos account activate` a short-lived token for (account, person, machine) carrying non-critical `uid`/`did` claims, and the device code from that pairing becomes this machine's refresh secret, kept in $BRAVOS_HOME/device.json (0600). refreshIfDue() trades the secret for a fresh token at the portal origin recorded at activation, once less than half the token's term is left (or it has expired, or the file is missing), verifies the new token with the same offline verifier before writing it, and fails OPEN on a network error, a timeout or a 5xx — the held token keeps working for whatever term it has. A refusal that means the machine is no longer licensed (401 invalid_device; 403 device_revoked, licence_unassigned, account_unavailable) removes the token and the device file, so the machine is back on Free and says why. A token supplied through BRAVOS_LICENCE / BRAVOS_LICENSE (CI) is never refreshed. Dependency-free (node:fs and the global fetch) so the session hook and the CLI share this one implementation."
2
2
  import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
- import { ACCOUNT_LICENCES, ACCOUNT_UPGRADE, LICENCE_ENV, LICENCE_ENV_ALT, LICENCE_FILES, bravosHome, verify } from './licence.mjs';
4
+ import { ACCOUNT_LICENCES, ACCOUNT_ORIGIN, ACCOUNT_UPGRADE, LICENCE_ENV, LICENCE_ENV_ALT, LICENCE_FILES, bravosHome, verify } from './licence.mjs';
5
5
  import { machineFingerprint } from './machine.mjs';
6
6
 
7
7
  export const DEVICE_FILE = 'device.json';
8
8
  export const REFRESH_PATH = '/api/v1/cli/licence/refresh';
9
9
  export const DEVICES_PATH = '/api/v1/cli/devices';
10
10
  export const REVOKE_PATH = '/api/v1/cli/devices/revoke';
11
+ export const TRIAL_PATH = '/api/v1/cli/licence/trial';
12
+ /** How often a trial licence asks whether its team's trial still runs. */
13
+ export const TRIAL_CHECK_SECONDS = 6 * 3600;
14
+ export const TRIAL_CHECK_FILE = 'trial-check.json';
11
15
  export const REFRESH_TIMEOUT_MS = 5000;
12
16
  /** After a refresh that could not reach the portal, an unforced refresh waits this long before trying again. */
13
17
  export const RETRY_AFTER_FAILURE_SECONDS = 15 * 60;
@@ -182,7 +186,9 @@ export async function refreshIfDue(env = process.env, opts = {}) {
182
186
  if ((env[LICENCE_ENV] || '').trim() || (env[LICENCE_ENV_ALT] || '').trim()) return { outcome: 'skipped', reason: 'environment' };
183
187
  if (env.BRAVOS_NO_FETCH || env.BRAVOS_REFRESH === 'off') return { outcome: 'skipped', reason: 'disabled' };
184
188
  const device = readDevice(env);
185
- if (!device) return { outcome: 'skipped', reason: 'no-device' };
189
+ // A TRIAL LICENCE HAS NO DEVICE RECORD: the team's trial is one licence for the
190
+ // account. It is not renewed; it only asks whether the trial still runs.
191
+ if (!device) return await checkTrialIfDue(env, { ...opts, now, fetch: f, force });
186
192
  const file = licencePath(env);
187
193
  const token = file ? readToken(file) : null;
188
194
  if (token) {
@@ -255,3 +261,86 @@ export async function refreshIfDue(env = process.env, opts = {}) {
255
261
  return { outcome: 'kept', reason: e && e.message ? e.message : 'error' };
256
262
  }
257
263
  }
264
+
265
+ const trialCheckPath = (env) => {
266
+ const home = bravosHome(env);
267
+ return home ? join(home, TRIAL_CHECK_FILE) : null;
268
+ };
269
+
270
+ /** The portal origin for a trial check: BRAVOS_ACCOUNT_ORIGIN when it is a plain origin (a local portal), else the account portal. */
271
+ const trialOrigin = (env) => {
272
+ const raw = (env.BRAVOS_ACCOUNT_ORIGIN || '').trim();
273
+ return /^https?:\/\/[^/\s]+$/.test(raw) ? raw : ACCOUNT_ORIGIN;
274
+ };
275
+
276
+ /** What to tell the person when their team's trial has ended. */
277
+ export function trialEndedNote(reason) {
278
+ return reason === 'plan'
279
+ ? `Your team is on a plan now, so the trial licence on this machine was removed. Run bravos account activate to sign this machine in with your licence (ask an owner or admin for one if you do not have it: ${ACCOUNT_LICENCES}).`
280
+ : `Your team's trial has ended, so this machine is back on Free. Choose a plan at ${ACCOUNT_UPGRADE} to keep the Team features.`;
281
+ }
282
+
283
+ // @comment -- "For a trial licence (one licence for the whole team, so no device record): at most every TRIAL_CHECK_SECONDS, POST <portal>/api/v1/cli/licence/trial with the trial licence itself as the bearer and ask whether the team's trial still runs. 200: it does. 403 trial_ended: the team bought a plan or the trial was ended, so licence.jwt is removed (only that file) and the person is told why on the next briefing. Anything else, no answer or a timeout keeps the licence: fail open, as every renewal does. Never throws."
284
+ // @exposes #licence-refresh to #token-disclosure [low] cwe:CWE-200 -- "Entry: checkTrialIfDue() at session start. Input: licence.jwt and env.BRAVOS_ACCOUNT_ORIGIN. Sink: fetch(trialOrigin(env) + TRIAL_PATH) with the licence as the Authorization bearer. Absent control: an origin taken from the environment unchecked would send the trial licence to any host."
285
+ // @mitigates #licence-refresh against #token-disclosure using #fixed-origin -- "The origin is the account portal, or BRAVOS_ACCOUNT_ORIGIN only when it is a plain http(s) origin; no proxy is read and the request has a timeout"
286
+ export async function checkTrialIfDue(env = process.env, opts = {}) {
287
+ const now = opts.now ?? Math.floor(Date.now() / 1000);
288
+ const f = opts.fetch ?? globalThis.fetch;
289
+ try {
290
+ const file = licencePath(env);
291
+ const token = file ? readToken(file) : null;
292
+ if (!token) return { outcome: 'skipped', reason: 'no-device' };
293
+ const v = verify(token);
294
+ const claims = v.state === 'invalid' ? null : claimsOf(token);
295
+ if (!claims || !claims.trial || typeof claims.did === 'string') return { outcome: 'skipped', reason: 'no-device' };
296
+ const stamp = trialCheckPath(env);
297
+ if (!opts.force && stamp) {
298
+ try {
299
+ const at = JSON.parse(readFileSync(stamp, 'utf8'))?.at;
300
+ if (typeof at === 'number' && now - at < TRIAL_CHECK_SECONDS && at <= now + 60) return { outcome: 'fresh', reason: 'trial-checked' };
301
+ } catch {
302
+ /* never checked */
303
+ }
304
+ }
305
+ let r;
306
+ try {
307
+ r = await f(`${trialOrigin(env)}${TRIAL_PATH}`, {
308
+ method: 'POST',
309
+ headers: { 'User-Agent': opts.userAgent ?? 'bravos-cli', Accept: 'application/json', Authorization: `Bearer ${token}` },
310
+ signal: AbortSignal.timeout(opts.timeoutMs ?? REFRESH_TIMEOUT_MS),
311
+ });
312
+ } catch {
313
+ return { outcome: 'kept', reason: 'unreachable' };
314
+ }
315
+ let body = null;
316
+ try {
317
+ body = await r.json();
318
+ } catch {
319
+ body = null;
320
+ }
321
+ if (r.status === 200) {
322
+ if (stamp) {
323
+ try {
324
+ writePrivate(stamp, JSON.stringify({ at: now }) + '\n');
325
+ } catch {
326
+ /* the stamp only spaces the checks */
327
+ }
328
+ }
329
+ return { outcome: 'fresh', reason: 'trial-running' };
330
+ }
331
+ if (r.status === 403 && body?.error === 'trial_ended') {
332
+ const why = body.reason === 'plan' ? 'plan' : 'ended';
333
+ try {
334
+ rmSync(file);
335
+ } catch {
336
+ /* already gone */
337
+ }
338
+ const note = trialEndedNote(why);
339
+ rememberNote(env, 'revoked', note, now);
340
+ return { outcome: 'revoked', reason: `trial_${why}`, note };
341
+ }
342
+ return { outcome: 'kept', reason: `http-${r.status}` };
343
+ } catch (e) {
344
+ return { outcome: 'kept', reason: e && e.message ? e.message : 'error' };
345
+ }
346
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bugb-technologies/bravos",
3
- "version": "1.22.0",
3
+ "version": "1.24.0",
4
4
  "description": "Skills pack and installer that make Claude Code and Codex power users of guardlink (threat-model-as-code) and cert-x-gen (pentest-as-code).",
5
5
  "keywords": [
6
6
  "security",