diff --git a/CHANGELOG.md b/CHANGELOG.md index 155e4e3..a203b82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,18 @@ # Changelog +## [0.9.1] - 2026-11-10 + +### Fixed + +- **Paid features are unlocked on the first paint.** A signed-in page now reads the plan's features, the billing state and the flag definitions before Angular renders it (each read capped at 1.5 seconds), so a paying user no longer sees "Upgrade to use this" flash on a plan-gated feature. Flags also re-check when the plan, its features or a plan limit change, so a feature unlocks straight after an upgrade and locks after a downgrade, with no reload. +- **Billing screens stay current.** The plan picker, the subscription badge and the billing notice re-read when the sign-in renews, when a plan or subscription changes in Bridge, and when the tab regains focus after 30 seconds. A plan added or changed in Bridge shows without a reload, and the current plan stays on screen while it re-reads. A plan list that comes back empty or fails to load now offers **Try again** instead of "No plans available." +- **A flag on a route is a live kill switch.** Switching off the flag a route rule names now moves someone already on that page to the rule's `redirectTo` within about a second, without a click. A flag that changed while live updates were down is picked up when they reconnect. + +### Changed + +- **Guides follow "every gate is a flag".** The billing and feature-flags guides open with the rule and end with `npx @nebulr-group/bridge-cli check gates`. A paid feature is taught as a flag ruled on the plan's feature, with direct plan checks kept as the exception. The guides name the MCP tools next to the CLI commands, the team guide teaches seat limits with `seatsMetric`, and the live-updates page explains each status reason and links the troubleshooting page. +- **The guides are checked against the package.** A test now fails if a guide imports, renders or configures something the package does not have. + ## [0.9.0] - 2026-11-10 ### Changed diff --git a/bridge-angular/package.json b/bridge-angular/package.json index 3ad37cb..bc23ebe 100644 --- a/bridge-angular/package.json +++ b/bridge-angular/package.json @@ -1,6 +1,6 @@ { "name": "@nebulr-group/bridge-angular", - "version": "0.9.0", + "version": "0.9.1", "description": "The Bridge for Angular: sign-in, workspaces and roles, feature flags, Stripe subscriptions and plan limits with providers and route helpers.", "author": "Iman Pouya", "license": "MIT", diff --git a/bridge-angular/src/doc-currency.spec.ts b/bridge-angular/src/doc-currency.spec.ts new file mode 100644 index 0000000..720f9e6 --- /dev/null +++ b/bridge-angular/src/doc-currency.spec.ts @@ -0,0 +1,269 @@ +// TBP-705 — the guides this repo serves to AI agents (mcp/, learning/, README.md, +// read from GitHub main by the Bridge MCP server) must not teach what the rule +// forbids. The owner's rule (2026-09-29): every gate in app code is a flag, and +// its rule says why — a privilege, a plan feature +// (`bridge:billing.entitlement. eq true`) or a rollout. App code never reads +// a role, a privilege list, the plan or a plan feature to decide what someone may +// see or do. Browser-only counting is a complete, first-class way to run limits. +// +// A sentence that tells the reader NOT to do it is allowed, and so is anything +// in the one section a guide may have whose heading says "Exceptions". +// +// The pattern list, the negation list and the Exceptions scoping MIRROR +// bridge-cli `src/gate-rules.ts` (DOC_FORBIDDEN / docGateViolations), which is +// the source of truth and also drives `bridge check gates`. Keep them the same: +// change it there first, then copy it here. +// +// Angular port (TBP-705 parity): the same patterns, plus the Angular spellings +// of a direct plan-feature check (`*bridgeEntitled`, `injectEntitlements()`). +// Lives in src/ (not src/lib) and is a .spec.ts, so the library build never +// includes it. + +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +// ── Mirror of bridge-cli src/gate-rules.ts (docs part) ────────────────────── + +const DOC_FORBIDDEN: Array<[string, RegExp]> = [ + ['a role compared in code', /\b(?:user|session|claims|token|me|currentUser|profile|locals\.user|req\.user|\$user|\$profile)\??\.role\s*(?:===|!==|==|!=)/], + ['a role compared in code', /\brole\s*(?:===|!==|==|!=)\s*['"`]/i], + ['a role list checked in code', /\[\s*['"][A-Z_]+['"](?:\s*,\s*['"][A-Z_]+['"])*\s*\]\s*\.includes\(/], + ['a role checked in code', /\bhasRole\s*\(/], + ['a role decorator on a handler', /@RequireRole\s*\(/], + ['a role check on the page', /\brole check\b[^.\n]{0,30}\b(?:in|on) (?:the |your )?(?:page|component|code|handler|layout|controller)/i], + ['a role check on the page', /\bcheck\w*\b[^.\n]{0,30}\brole\b[^.\n]{0,30}\b(?:in|on) (?:the |your )?(?:page|component|code|layout)\b/i], + ['"target a role instead"', /target a role instead/i], + ['privileges read in code', /\bprivileges\s*\??\.\s*(?:includes|some|indexOf|has)\s*\(/], + ['a direct plan-feature check', / { + if (/^\s*(?:```|~~~)/.test(line)) inFence = !inFence; + const heading = inFence ? null : HEADING.exec(line); + if (heading) { + const level = heading[1].length; + if (exceptionLevel && level <= exceptionLevel) exceptionLevel = 0; + if (/exception/i.test(heading[2])) exceptionLevel = level; + return; + } + if (exceptionLevel) return; + for (const sentence of line.split(/(?<=[.!?])\s+/)) { + if (NEGATED.test(sentence)) continue; + for (const [rule, pattern] of DOC_FORBIDDEN) { + if (pattern.test(sentence)) out.push({ line: i + 1, rule, text: sentence.trim() }); + } + } + }); + return out; +} + +// ── This repo's agent-facing docs ─────────────────────────────────────────── + +const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); +// (this file is bridge-angular/src/doc-currency.spec.ts; REPO is the repo root) + +function markdownFiles(dir: string): string[] { + return readdirSync(dir).flatMap((name) => { + const path = join(dir, name); + if (statSync(path).isDirectory()) return markdownFiles(path); + return name.endsWith('.md') ? [path] : []; + }); +} + +const read = (file: string) => readFileSync(file, 'utf8'); +const agentDocs = [...markdownFiles(join(REPO, 'mcp')), ...markdownFiles(join(REPO, 'learning')), join(REPO, 'README.md')]; + +describe('no agent-facing guide teaches a direct role, privilege or plan check, or talks browser counting down — TBP-705', () => { + it('finds the guides (guards against scanning nothing)', () => { + expect(agentDocs.length).toBeGreaterThan(10); + expect(agentDocs).toContain(join(REPO, 'mcp', 'billing-prompt.md')); + }); + + it.each(agentDocs.map((f) => [relative(REPO, f), f]))('%s', (_name, file) => { + expect(docGateViolations(read(file))).toEqual([]); + }); + + // Owner 2026-09-29: the trust trade-off of browser counting belongs to human + // docs only. mcp/ and learning/ are served to agents; the README may say it once. + it('the browser-counting trust trade-off is not in mcp/ or learning/, and at most once in the README', () => { + const TRADE_OFF = /trusts the browser|could report less than/i; + const inAgentGuides = agentDocs + .filter((f) => f !== join(REPO, 'README.md')) + .filter((f) => TRADE_OFF.test(read(f))) + .map((f) => relative(REPO, f)); + expect(inAgentGuides).toEqual([]); + expect(read(join(REPO, 'README.md')).match(new RegExp(TRADE_OFF.source, 'gi'))?.length ?? 0).toBeLessThanOrEqual(1); + }); + + describe('goes red on a planted bad line', () => { + it.each([ + 'For admin-only pages, add a role check on the page: `if (user.role === "ADMIN")`.', + "Gate the page with `{#if $auth.user.role == 'ADMIN'}`.", + "Gate the link with `@if (profile()?.role === 'ADMIN')`.", + 'Wrap the chart in ``.', + "Show it when `this.bridge.tenant.entitlements.can('exports')`.", + "Put `@RequireRole('ADMIN')` on the handler.", + 'Check the role in the component before rendering the button.', + "Show analytics when `tenant.plan === 'pro'`.", + "if (plan === 'pro') showAnalytics();", + 'const isPro = subscription.plan.key === "pro";', + '{ "conditions": [{ "attribute": "tenant.plan", "operator": "eq", "values": ["pro"] }] }', + 'Wrap the chart in ``.', + "Show the button when `$entitlements.can('exports')`.", + "Put `@RequireEntitlement('analytics')` on the handler.", + "const canManageTeam = ['OWNER', 'ADMIN'].includes(role);", + "Show the link when `privileges.includes('USER_WRITE')`.", + "{ path: '/reports/*', privilege: 'REPORTS_VIEW' }", + "{ path: '/reports/*', privilege: 'AUTHENTICATED', plans: ['pro'] }", + 'Browser counting is display, not enforcement.', + 'Only a backend can refuse a click over the limit.', + 'Offer "Browser only (demo-grade)" as the last option.', + 'A frontend-only app cannot enforce a limit.', + 'Counting in the browser is not production-ready.', + ])('%s', (bad) => { + expect(docGateViolations(bad)).not.toEqual([]); + }); + + it('and in a real guide file, not only in isolation', () => { + const planted = `${read(join(REPO, 'mcp', 'team-prompt.md'))}\nShow the Team link when \`['OWNER','ADMIN'].includes(role)\`.\n`; + const found = docGateViolations(planted); + expect(found.length).toBeGreaterThan(0); + for (const v of found) expect(v.text).toContain("['OWNER','ADMIN'].includes(role)"); + }); + }); + + describe("stays green on the rule's own sentences", () => { + it.each([ + '**Every gate in app code is a flag.** A link, a page, a button, an endpoint: if some people get it and others do not, the code asks a flag, and the flag\'s rule says why: a privilege (`privileges contains "USER_WRITE"`), a plan feature (`bridge:billing.entitlement.analytics eq true`) or a rollout.', + 'App code never reads a role, a privilege list, the plan or a plan feature to decide what someone may see or do.', + 'Control it with a flag rule, never with a role check written into the app\'s code.', + 'Never gate the Team link with `[\'OWNER\',\'ADMIN\'].includes(role)`.', + 'A role rule (`user.role eq "ADMIN"`) is fine when the developer means the role itself.', + "{ match: '/admin/*', featureFlag: 'admin-area', redirectTo: '/' }", + "{ path: '/health', privilege: 'ANONYMOUS' }", + 'Browser-only counting is a first-class, complete way to run limits.', + 'Never describe browser counting as demo-grade.', + ])('%s', (good) => { + expect(docGateViolations(good)).toEqual([]); + }); + + it('a direct plan-feature check inside the Exceptions section, and only there', () => { + const guide = [ + '## Gating', + 'Use ``.', + '## Exceptions', + 'When the developer asks for no flag, `*bridgeEntitled="\'analytics\'"` reads the plan directly.', + '### Details', + "`$entitlements.can('analytics')` is the same check in script.", + '## Next', + 'Wrap it in ``.', + ].join('\n'); + expect(docGateViolations(guide).map((v) => v.line)).toEqual([8]); + }); + }); +}); + +// ── TBP-763 — seats ───────────────────────────────────────────────────────── +// +// Owner decisions 2026-09-29: seats are a plan limit the app names (e.g. +// `seats`), kind gauge, counted by Bridge from membership (`--source +// membership`). There is no built-in `users` seat metric. The limit is enforced +// where invites start — `seatsMetric="seats"` on the built-in team page, or +// `@RequireQuota('seats')` on the app's own invite handler — because Bridge's +// invite API does not refuse at the limit. Never a flag or an entitlement. + +const SEAT_FORBIDDEN: Array<[string, RegExp]> = [ + ['`users` as the built-in seat metric', /\bseats?\b\**\s*\(\s*`(?:metric:\s*)?["']?users["']?`\s*\)/i], + ['`users` as the built-in seat metric', /@RequireQuota\(\s*['"]users['"]/], + ['`users` as the built-in seat metric', /--metric\s+users\b|"metric"\s*:\s*"users"|\bmetric:\s*["']users["']/], + ['seats gated with a flag or an entitlement', /\bseats?\b[^.\n]{0,60}(?: { + for (const sentence of line.split(/(?<=[.!?])\s+/)) { + if (NEGATED.test(sentence) || /\bno built-in\b/i.test(sentence)) continue; + for (const [rule, pattern] of SEAT_FORBIDDEN) { + if (pattern.test(sentence)) out.push({ line: i + 1, rule, text: sentence.trim() }); + } + } + }); + return out; +} + +const SEATS_CLI = 'bridge plan quota set --metric seats --limit N --policy hard --kind gauge --source membership'; + +describe('seats are a plan limit the app names, counted from membership — TBP-763', () => { + it.each(agentDocs.map((f) => [relative(REPO, f), f]))('%s', (_name, file) => { + expect(seatViolations(read(file))).toEqual([]); + }); + + it.each([['mcp/team-prompt.md'], ['mcp/billing-prompt.md']])('%s teaches the seat setup and both enforcement points', (file) => { + const guide = read(join(REPO, file)); + expect(guide).toContain(SEATS_CLI); + expect(guide).toContain('seatsMetric="seats"'); + expect(guide).toContain("@RequireQuota('seats')"); + expect(guide).toMatch(/invite API does not refuse at the limit/i); + expect(guide).toMatch(/built-in team page or the app's own invite handler|built-in team page, or the app's own invite handler/i); + expect(guide).toMatch(/never gate seats with a flag or an entitlement/i); + }); + + describe('goes red on a planted bad line', () => { + it.each([ + 'Seats (`metric: "users"`) are counted by Bridge from workspace members.', + '**Seats** (`users`) are a gauge Bridge keeps itself.', + "Put `@RequireQuota('users')` on your invite handler.", + 'bridge plan quota set free --metric users --limit 2 --policy hard', + 'Gate the invite button on seats with a flag rule.', + 'Gate seats with `` around Invite.', + 'Put the seat count behind an entitlement.', + ])('%s', (bad) => { + expect(seatViolations(bad)).not.toEqual([]); + }); + }); + + describe('stays green on the guides’ own sentences', () => { + it.each([ + 'There is no built-in `users` metric.', + 'Never gate seats with a flag or an entitlement: a seat count is a limit.', + SEATS_CLI, + "`@RequireQuota('seats')` on that backend handler.", + ])('%s', (good) => { + expect(seatViolations(good)).toEqual([]); + }); + }); +}); diff --git a/bridge-angular/src/guide-drift.spec.ts b/bridge-angular/src/guide-drift.spec.ts new file mode 100644 index 0000000..bcf6e7f --- /dev/null +++ b/bridge-angular/src/guide-drift.spec.ts @@ -0,0 +1,459 @@ +// Guide drift — the guides this repo serves to people and to AI agents (mcp/, +// learning/, README.md; the Bridge MCP server reads them from GitHub main) may +// only name what the package really has. A guide that imports a removed export, +// renders a component under an old selector, or binds an input the component +// never had produces code that does not compile, and an agent following it has +// no way to know. +// +// What is checked, read from the package source with the TypeScript compiler +// (nothing is listed by hand, so a rename in the code turns this red): +// - every name imported from '@nebulr-group/bridge-angular' is exported by +// src/public-api.ts, and no other subpath than './styles.css' is imported; +// - every `` element is a component selector, and every attribute +// bound on it is one of that component's inputs or outputs; +// - every `*bridgeX` / `[bridgeX]` is a directive selector or a directive input; +// - an SDK-looking name in inline code (`FooComponent`, `injectQuota()`, +// `createQuotaSignal()`, `bridgeAuthGuard()`, …) is exported; +// - `bridge.` (the injected BridgeService) names a real member; +// - `billing.