bailinghub 0.8.0 → 0.9.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.
Files changed (209) hide show
  1. package/.dockerignore +6 -0
  2. package/.npmignore +6 -0
  3. package/CONTRIBUTING.md +4 -0
  4. package/GOVERNANCE.md +9 -0
  5. package/README.en.md +8 -6
  6. package/README.md +8 -6
  7. package/SECURITY.md +8 -2
  8. package/THIRD_PARTY_NOTICES.md +17 -17
  9. package/docker-compose.images.yml +2 -2
  10. package/docs/ARCHITECTURE.md +1 -1
  11. package/docs/CHANGELOG.en.md +22 -1
  12. package/docs/CHANGELOG.md +22 -1
  13. package/docs/COMPATIBILITY.en.md +8 -0
  14. package/docs/IMPLEMENTATION_STATUS.en.md +73 -0
  15. package/docs/IMPLEMENTATION_STATUS.md +73 -0
  16. package/docs/INDEPENDENT_VALIDATION.en.md +4 -4
  17. package/docs/INDEPENDENT_VALIDATION.md +4 -4
  18. package/docs/KERNEL_HOST_API.en.md +18 -0
  19. package/docs/KERNEL_HOST_API.md +18 -0
  20. package/docs/MODEL_BILLING.en.md +123 -0
  21. package/docs/MODEL_BILLING.md +125 -0
  22. package/docs/PERIOD_ALLOWANCE_UPGRADE.en.md +31 -0
  23. package/docs/PERIOD_ALLOWANCE_UPGRADE.md +31 -0
  24. package/docs/README.en.md +8 -1
  25. package/docs/README.md +7 -0
  26. package/docs/RELEASE_NOTES_NEXT.en.md +4 -2
  27. package/docs/RELEASE_NOTES_NEXT.md +4 -2
  28. package/docs/RELEASE_NOTES_v0.9.0.en.md +45 -0
  29. package/docs/RELEASE_NOTES_v0.9.0.md +45 -0
  30. package/docs/RELEASE_NOTES_v0.9.1.en.md +38 -0
  31. package/docs/RELEASE_NOTES_v0.9.1.md +38 -0
  32. package/docs/UPGRADE_v0.9.0.en.md +54 -0
  33. package/docs/UPGRADE_v0.9.0.md +54 -0
  34. package/docs/UPGRADE_v0.9.1.en.md +39 -0
  35. package/docs/UPGRADE_v0.9.1.md +39 -0
  36. package/docs//345/205/274/345/256/271/346/200/247/344/270/216/345/215/207/347/272/247.md +8 -0
  37. package/package.json +5 -4
  38. package/scripts/check-doc-links.mjs +6 -0
  39. package/scripts/check-image-tags.sh +1 -1
  40. package/scripts/check-release-consistency.test.mjs +2 -2
  41. package/scripts/dependency-audit.mjs +134 -0
  42. package/scripts/dependency-audit.test.mjs +125 -0
  43. package/scripts/install.sh +1 -1
  44. package/scripts/osps-results.py +114 -0
  45. package/scripts/publish-images.sh +1 -1
  46. package/scripts/release-audit.mjs +2 -0
  47. package/scripts/sdk-runtime-test.mjs +6 -0
  48. package/scripts/verify-billing-install-upgrade.mjs +225 -0
  49. package/scripts/verify-github-repo.mjs +2 -0
  50. package/sdk/node/README.md +17 -0
  51. package/sdk/node/examples/billing.mjs +21 -0
  52. package/sdk/node/package.json +5 -1
  53. package/sdk/node/src/index.mjs +2 -0
  54. package/sdk/node/src/usage.d.mts +74 -0
  55. package/sdk/node/src/usage.mjs +62 -0
  56. package/sdk/node/tests/usage-types.mts +23 -0
  57. package/sdk/node/tests/usage.test.mjs +81 -0
  58. package/sdk/php7/README.md +19 -2
  59. package/sdk/php7/examples/billing.php +27 -0
  60. package/sdk/php7/examples/well-known.php +1 -1
  61. package/sdk/php7/src/ToolSpec.php +1 -1
  62. package/sdk/php7/src/UsageClient.php +95 -0
  63. package/sdk/php7/src/UsageClientException.php +22 -0
  64. package/sdk/php7/tests/billing-core-http.php +59 -0
  65. package/sdk/php7/tests/usage-client.php +78 -0
  66. package/security/dependency-audit-exceptions.json +192 -0
  67. package/sql/063_usage_model_billing.sql +153 -0
  68. package/sql/064_period_plan_allowance.sql +25 -0
  69. package/sql/README.en.md +12 -4
  70. package/sql/README.md +14 -6
  71. package/src/app/auth.ts +2 -0
  72. package/src/app/kernel-usage-lifecycle.mysql.test.ts +325 -0
  73. package/src/app/kernel.ts +10 -0
  74. package/src/app/oss-edition.ts +1 -0
  75. package/src/infrastructure/config/configstore.ts +6 -0
  76. package/src/modules/usage/allowance-reset.mysql.test.ts +122 -0
  77. package/src/modules/usage/background-work.test.ts +144 -0
  78. package/src/modules/usage/background-work.ts +50 -0
  79. package/src/modules/usage/billing-contracts.ts +59 -0
  80. package/src/modules/usage/billing-decimal.test.ts +22 -0
  81. package/src/modules/usage/billing-decimal.ts +36 -0
  82. package/src/modules/usage/billing-external.ts +39 -0
  83. package/src/modules/usage/billing-gateway.mysql.test.ts +24 -0
  84. package/src/modules/usage/billing-ledger.test.ts +51 -0
  85. package/src/modules/usage/billing-ledger.ts +104 -0
  86. package/src/modules/usage/billing-presentation.mysql.test.ts +95 -0
  87. package/src/modules/usage/billing-presentation.test.ts +49 -0
  88. package/src/modules/usage/billing-presentation.ts +34 -0
  89. package/src/modules/usage/billing-prices.mysql.test.ts +88 -0
  90. package/src/modules/usage/billing-repository.mysql.test.ts +181 -0
  91. package/src/modules/usage/billing-repository.ts +465 -0
  92. package/src/modules/usage/contracts.ts +49 -0
  93. package/src/modules/usage/dynamic-plan-models.mysql.test.ts +221 -0
  94. package/src/modules/usage/errors.ts +19 -0
  95. package/src/modules/usage/http.ts +85 -0
  96. package/src/modules/usage/identity-revocation.mysql.test.ts +286 -0
  97. package/src/modules/usage/identity.mysql.test.ts +120 -0
  98. package/src/modules/usage/identity.ts +303 -0
  99. package/src/modules/usage/issuer-sdk-billing.mysql.test.ts +92 -0
  100. package/src/modules/usage/model-gateway.mysql.test.ts +207 -0
  101. package/src/modules/usage/model-gateway.ts +236 -0
  102. package/src/modules/usage/model-tool-gateway.mysql.test.ts +137 -0
  103. package/src/modules/usage/model-tool-provider.test.ts +37 -0
  104. package/src/modules/usage/model-tool-provider.ts +110 -0
  105. package/src/modules/usage/model-tools.test.ts +36 -0
  106. package/src/modules/usage/model-tools.ts +62 -0
  107. package/src/modules/usage/period-allowance.mysql.test.ts +97 -0
  108. package/src/modules/usage/period.test.ts +26 -0
  109. package/src/modules/usage/period.ts +96 -0
  110. package/src/modules/usage/pricing.test.ts +178 -0
  111. package/src/modules/usage/pricing.ts +229 -0
  112. package/src/modules/usage/provider-failure.ts +37 -0
  113. package/src/modules/usage/provider-stream.test.ts +85 -0
  114. package/src/modules/usage/provider-stream.ts +77 -0
  115. package/src/modules/usage/provider.test.ts +67 -0
  116. package/src/modules/usage/provider.ts +142 -0
  117. package/src/modules/usage/repository.ts +541 -0
  118. package/src/modules/usage/service-availability.mysql.test.ts +68 -0
  119. package/src/modules/usage/service-availability.ts +13 -0
  120. package/src/modules/usage/service-delete.mysql.test.ts +87 -0
  121. package/src/modules/usage/stream-http.ts +32 -0
  122. package/src/modules/usage/test-harness.ts +109 -0
  123. package/src/modules/usage/usage-deletion.mysql.test.ts +312 -0
  124. package/src/modules/usage/usage-deletion.ts +119 -0
  125. package/src/modules/usage/validation.test.ts +18 -0
  126. package/src/modules/usage/validation.ts +33 -0
  127. package/src/routes/admin-billing-usage.ts +73 -0
  128. package/src/routes/admin-usage.ts +147 -0
  129. package/src/routes/admin.ts +4 -0
  130. package/src/routes/private.ts +8 -0
  131. package/web/connect/bailing-connect-php7.tgz +0 -0
  132. package/web/console/assets/Accounts-Bervi5JU.css +1 -0
  133. package/web/console/assets/Accounts-DKhw_QLr.js +3 -0
  134. package/web/console/assets/{AgentClients-Bf7sUUs_.js → AgentClients-CM4_5HaA.js} +1 -1
  135. package/web/console/assets/AgentTasks-BsG850Il.css +1 -0
  136. package/web/console/assets/AgentTasks-CkQgZTU5.js +2 -0
  137. package/web/console/assets/{Approvals-BIbZvInm.js → Approvals-B9O9TkbO.js} +1 -1
  138. package/web/console/assets/{Audit-KyPSmBdZ.js → Audit-2vDC1SPu.js} +1 -1
  139. package/web/console/assets/{BrandLockup-Sv5DU2G6.js → BrandLockup-BgASiRSE.js} +1 -1
  140. package/web/console/assets/{Channels-B9n4fbxg.js → Channels-A-GvkNBt.js} +1 -1
  141. package/web/console/assets/{ChatEntries-xsOCUXi_.js → ChatEntries-BLxymI67.js} +1 -1
  142. package/web/console/assets/{Clients-CI3DBDHf.js → Clients-DeNlmvS6.js} +1 -1
  143. package/web/console/assets/{Cost-JgNXQPlN.js → Cost-CBq_L4Kz.js} +1 -1
  144. package/web/console/assets/{Credentials-B5UUUdt0.js → Credentials-DmtbctNj.js} +1 -1
  145. package/web/console/assets/{Diagnostics-BMGciWQb.js → Diagnostics-BbcRDiA-.js} +1 -1
  146. package/web/console/assets/{Executors-CRbboOCZ.js → Executors-gGgmQrDt.js} +1 -1
  147. package/web/console/assets/{HelpTip-i-KJhf5s.js → HelpTip-Dtdt2tKR.js} +1 -1
  148. package/web/console/assets/{Kb-CgLNGjRp.js → Kb-lgY6OXUz.js} +2 -2
  149. package/web/console/assets/{Login-C52JmXzx.js → Login-DA6BASZd.js} +1 -1
  150. package/web/console/assets/{Projects-CDOvHPVS.js → Projects-DEbmB_sT.js} +1 -1
  151. package/web/console/assets/Routes-CyXV4Pba.css +1 -0
  152. package/web/console/assets/Routes-qS6LLoyS.js +124 -0
  153. package/web/console/assets/{Runs-DYNDXsqk.js → Runs-DG-VLRSc.js} +1 -1
  154. package/web/console/assets/{Setup-B91P6i1x.js → Setup-DEpVF5uw.js} +1 -1
  155. package/web/console/assets/Shell-DgoPgK1E.js +1 -0
  156. package/web/console/assets/Shell-ykb-tUfo.css +1 -0
  157. package/web/console/assets/{StorageBuckets-DkuDM0oX.js → StorageBuckets-DJtNN769.js} +1 -1
  158. package/web/console/assets/{SystemSettings-B7Mqj3k1.js → SystemSettings-0DEUgeTR.js} +1 -1
  159. package/web/console/assets/{SystemStatus-Db93b6dc.js → SystemStatus-CR1phiPE.js} +1 -1
  160. package/web/console/assets/{Targets-CuuIYeZO.js → Targets-D65l-IMB.js} +1 -1
  161. package/web/console/assets/{Tools-CHiqz9XZ.js → Tools-DqtrINrN.js} +1 -1
  162. package/web/console/assets/Usage-B5njXNjx.js +1 -0
  163. package/web/console/assets/Usage-CAeDGjrb.css +1 -0
  164. package/web/console/assets/UsageAccess-CGGaWTuj.css +1 -0
  165. package/web/console/assets/UsageAccess-ChnB4pjb.js +1 -0
  166. package/web/console/assets/UsageHelp-BBKIvbQ5.js +1 -0
  167. package/web/console/assets/UsageHelp-CSM4xO0K.css +1 -0
  168. package/web/console/assets/{index-QnmD7N7F.js → index-65JiiUr4.js} +1 -1
  169. package/web/console/assets/{index-Fi9gkGxV.css → index-Cxuc9OCj.css} +1 -1
  170. package/web/console/assets/index-sLKrJd_p.js +2 -0
  171. package/web/console/assets/{request-DeGya810.js → request-BpaimqEb.js} +1 -1
  172. package/web/console/assets/{schema-BqlqLw1R.js → schema-D0Z4kFCZ.js} +1 -1
  173. package/web/console/assets/{util-4bN2dv7B.js → util-DZYfJ5Zo.js} +1 -1
  174. package/web/console/assets/{vendor-element-CZoEjZr8.js → vendor-element-8cVcdt5T.js} +2 -2
  175. package/web/console/assets/{vendor-mammoth-BUEEDX6A.js → vendor-mammoth-CnDA23N0.js} +1 -1
  176. package/web/console/assets/vendor-vue-Co7x2FW6.js +29 -0
  177. package/web/console/index.html +4 -4
  178. package/web-admin/README.md +17 -0
  179. package/web-admin/package-lock.json +83 -85
  180. package/web-admin/src/components/UsageDeletionPreview.vue +44 -0
  181. package/web-admin/src/components/UsageHelp.vue +72 -0
  182. package/web-admin/src/components/UsageServiceReferences.vue +169 -0
  183. package/web-admin/src/layout/Shell.vue +22 -5
  184. package/web-admin/src/pages/Accounts.vue +3 -3
  185. package/web-admin/src/pages/AgentTasks.vue +2 -2
  186. package/web-admin/src/pages/Routes.vue +5 -1
  187. package/web-admin/src/pages/Usage.vue +2470 -0
  188. package/web-admin/src/pages/UsageAccess.vue +1147 -0
  189. package/web-admin/src/router.ts +8 -4
  190. package/web-admin/src/styles/base.css +57 -0
  191. package/web-admin/src/table-widths.ts +16 -1
  192. package/web-admin/src/usage-deletion.ts +40 -0
  193. package/web-admin/src/usage-management.ts +13 -0
  194. package/web-admin/src/usage-presentation.test.ts +21 -0
  195. package/web-admin/src/usage-presentation.ts +107 -0
  196. package/web-admin/src/usage-price-preview.test.ts +60 -0
  197. package/web-admin/src/usage-price-preview.ts +54 -0
  198. package/web-admin/tests/token-usage.browser.mjs +773 -0
  199. package/web-admin/tests/usage-access.browser.mjs +398 -0
  200. package/web/console/assets/Accounts-B4ePH5jp.css +0 -1
  201. package/web/console/assets/Accounts-BRCR3O0P.js +0 -3
  202. package/web/console/assets/AgentTasks--bqL_QKg.js +0 -2
  203. package/web/console/assets/AgentTasks-C8ox3TyS.css +0 -1
  204. package/web/console/assets/Routes-DkMIjMQA.css +0 -1
  205. package/web/console/assets/Routes-X9vHLpKW.js +0 -124
  206. package/web/console/assets/Shell-Bj6C8Hgo.css +0 -1
  207. package/web/console/assets/Shell-BsRa7bQQ.js +0 -1
  208. package/web/console/assets/index-UGvfF3Xr.js +0 -2
  209. package/web/console/assets/vendor-vue-B2uhHUfE.js +0 -29
@@ -0,0 +1,125 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { evaluateScope, collectUsage } from './dependency-audit.mjs';
7
+
8
+ const load = name => JSON.parse(readFileSync(new URL(name, import.meta.url), 'utf8'));
9
+ const policy = load('../security/dependency-audit-exceptions.json');
10
+ const now = new Date('2026-10-10T03:00:00Z');
11
+ function fixture(scope = 'core') {
12
+ const audit = { auditReportVersion: 2, vulnerabilities: structuredClone(policy.scopes[scope].knownAuditRows), metadata: { vulnerabilities: { info: 0, low: 0, moderate: 3, high: 0, critical: 0, total: 3 } } };
13
+ const lock = load(scope === 'core' ? '../package-lock.json' : '../web-admin/package-lock.json');
14
+ return { scope, audit, lock, usage: structuredClone(policy.scopes[scope].reviewedUsageFiles), policy: structuredClone(policy), now };
15
+ }
16
+ for (const scope of ['core', 'web-admin']) {
17
+ test(`${scope}: reviewed advisory passes while preserving all three moderate findings`, () => {
18
+ const result = evaluateScope(fixture(scope));
19
+ assert.equal(result.pass, true);
20
+ assert.equal(result.rawCounts.moderate, 3);
21
+ assert.equal(result.rawCounts.total, 3);
22
+ assert.equal(result.exceptedRows, 3);
23
+ assert.equal(result.unexceptedRows, 0);
24
+ });
25
+ }
26
+ test('exception expires at the exact boundary', () => {
27
+ const input = fixture(); input.now = new Date(policy.expiresAt);
28
+ assert.equal(evaluateScope(input).pass, false);
29
+ });
30
+ test('exception cannot begin before the approval period or exceed 30 days', () => {
31
+ const input = fixture(); input.now = new Date('2026-10-09T23:59:59Z');
32
+ assert.equal(evaluateScope(input).pass, false);
33
+ input.now = now; input.policy.expiresAt = '2026-11-10T00:00:00Z';
34
+ assert.equal(evaluateScope(input).pass, false);
35
+ });
36
+ test('a new moderate finding is blocked rather than globally ignored', () => {
37
+ const input = fixture();
38
+ input.audit.vulnerabilities.newPackage = { name: 'newPackage', severity: 'moderate', via: [{ url: 'https://github.com/advisories/GHSA-new' }], nodes: ['node_modules/newPackage'] };
39
+ input.audit.metadata.vulnerabilities.moderate++;
40
+ input.audit.metadata.vulnerabilities.total++;
41
+ const result = evaluateScope(input);
42
+ assert.equal(result.pass, false); assert.equal(result.rawCounts.moderate, 4); assert.equal(result.unexceptedRows, 1);
43
+ });
44
+ test('an additional advisory on the accepted package is blocked', () => {
45
+ const input = fixture(); input.audit.vulnerabilities['sprintf-js'].via.push({ url: 'https://github.com/advisories/GHSA-new', severity: 'high' });
46
+ assert.equal(evaluateScope(input).pass, false);
47
+ });
48
+ test('adding an unrelated advisory to both policy and audit cannot broaden the exception', () => {
49
+ const input = fixture();
50
+ const row = { name: 'anotherPackage', severity: 'moderate', via: [{ url: 'https://github.com/advisories/GHSA-new', severity: 'moderate' }], nodes: ['node_modules/anotherPackage'] };
51
+ input.policy.scopes.core.knownAuditRows.anotherPackage = structuredClone(row);
52
+ input.audit.vulnerabilities.anotherPackage = row;
53
+ input.audit.metadata.vulnerabilities.moderate++;
54
+ input.audit.metadata.vulnerabilities.total++;
55
+ assert.equal(evaluateScope(input).pass, false);
56
+ });
57
+ test('changing or appending an advisory in both policy and audit is blocked', () => {
58
+ const input = fixture();
59
+ for (const rows of [input.policy.scopes.core.knownAuditRows, input.audit.vulnerabilities]) {
60
+ rows['sprintf-js'].via[0].url = 'https://github.com/advisories/GHSA-new';
61
+ }
62
+ assert.equal(evaluateScope(input).pass, false);
63
+ const next = fixture();
64
+ for (const rows of [next.policy.scopes.core.knownAuditRows, next.audit.vulnerabilities]) {
65
+ rows['sprintf-js'].via.push({ url: 'https://github.com/advisories/GHSA-new', severity: 'moderate' });
66
+ }
67
+ assert.equal(evaluateScope(next).pass, false);
68
+ });
69
+ test('rewriting the reviewed dependency chain in both policy and audit is blocked', () => {
70
+ const input = fixture();
71
+ for (const rows of [input.policy.scopes.core.knownAuditRows, input.audit.vulnerabilities]) {
72
+ rows.argparse.via = ['anotherPackage'];
73
+ rows['sprintf-js'].effects = ['anotherPackage'];
74
+ }
75
+ assert.equal(evaluateScope(input).pass, false);
76
+ });
77
+ test('removing a reviewed policy row cannot redefine the approved exception', () => {
78
+ const input = fixture();
79
+ delete input.policy.scopes.core.knownAuditRows.argparse;
80
+ delete input.audit.vulnerabilities.argparse;
81
+ input.audit.metadata.vulnerabilities.moderate--;
82
+ input.audit.metadata.vulnerabilities.total--;
83
+ assert.equal(evaluateScope(input).pass, false);
84
+ });
85
+ test('a changed audit node or suggested fix cannot silently broaden the exception', () => {
86
+ const input = fixture(); input.audit.vulnerabilities['sprintf-js'].nodes.push('node_modules/new/node_modules/sprintf-js');
87
+ assert.equal(evaluateScope(input).pass, false);
88
+ const next = fixture(); next.audit.vulnerabilities['sprintf-js'].fixAvailable = true;
89
+ assert.equal(evaluateScope(next).pass, false);
90
+ });
91
+ test('a changed dependency version or additional installed copy is blocked', () => {
92
+ const input = fixture(); input.lock.packages['node_modules/mammoth'].version = '1.13.0';
93
+ assert.equal(evaluateScope(input).pass, false);
94
+ const next = fixture(); next.lock.packages['node_modules/new/node_modules/sprintf-js'] = { version: '1.0.3' };
95
+ assert.equal(evaluateScope(next).pass, false);
96
+ });
97
+ test('a new package consuming the same vulnerable copy is blocked', () => {
98
+ const input = fixture(); input.lock.packages['node_modules/new-consumer'] = { version: '1.0.0', dependencies: { 'sprintf-js': '~1.0.2' } };
99
+ assert.equal(evaluateScope(input).pass, false);
100
+ });
101
+ test('new CLI usage and modified reviewed library usage are blocked', () => {
102
+ const input = fixture(); input.usage['src/new-cli.ts'] = 'unreviewed';
103
+ assert.equal(evaluateScope(input).pass, false);
104
+ const next = fixture(); next.usage['src/adapters/llm/file.ts'] = 'modified';
105
+ assert.equal(evaluateScope(next).pass, false);
106
+ });
107
+ test('filesystem inventory detects a new source CLI and package script CLI', () => {
108
+ const root = mkdtempSync(join(tmpdir(), 'dependency-audit-usage-'));
109
+ try {
110
+ mkdirSync(join(root, 'src'));
111
+ writeFileSync(join(root, 'src/new-cli.ts'), "spawn('mammoth', ['input.docx']);\n");
112
+ writeFileSync(join(root, 'package.json'), JSON.stringify({ scripts: { convert: 'mammoth input.docx' } }));
113
+ const usage = collectUsage(root, 'core');
114
+ assert.ok(usage['src/new-cli.ts']);
115
+ assert.ok(usage['package.json#scripts.convert']);
116
+ const input = fixture(); input.usage = usage;
117
+ assert.equal(evaluateScope(input).pass, false);
118
+ } finally { rmSync(root, { recursive: true, force: true }); }
119
+ });
120
+ test('failed audit payload and misleading aggregate counts fail closed', () => {
121
+ const input = fixture(); input.audit.error = { code: 'EACCESS' };
122
+ assert.equal(evaluateScope(input).pass, false);
123
+ const next = fixture(); next.audit.metadata.vulnerabilities.total = 0;
124
+ assert.equal(evaluateScope(next).pass, false);
125
+ });
@@ -275,7 +275,7 @@ write_env() {
275
275
  TOOL_SECRET="${DEMO_TOOL_SECRET:-$(secret)}"
276
276
  CLIENT_TOKEN="${DEMO_CLIENT_TOKEN:-$(secret)}"
277
277
  IMAGE_TAG="${BAILING_IMAGE_TAG:-$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$APP_DIR/package.json" | head -1)}"
278
- [ -n "$IMAGE_TAG" ] || IMAGE_TAG="0.8.0"
278
+ [ -n "$IMAGE_TAG" ] || IMAGE_TAG="0.9.1"
279
279
  IMAGE_REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_IMAGE_REGISTRY}"
280
280
  IMAGE_NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_IMAGE_NAMESPACE}"
281
281
  cat > "$ENV_FILE" <<EOF
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env python3
2
+ """Validate the pinned scanner's JSON; successful collection is not compliance."""
3
+
4
+ import collections
5
+ import json
6
+ import os
7
+ import pathlib
8
+ import re
9
+ import sys
10
+
11
+ CATALOG = "osps-baseline-2026-08"
12
+ RESULTS = ("Passed", "Failed", "Needs Review", "Not Applicable", "Not Run", "Unknown")
13
+
14
+
15
+ def require(condition, message):
16
+ if not condition:
17
+ raise ValueError(message)
18
+
19
+
20
+ def inspect_results(document):
21
+ require(isinstance(document, dict), "result must be a JSON object")
22
+ require(document.get("service-name") == "pvtr", "unexpected scanner service")
23
+ require(document.get("plugin-name") == "github-repo", "unexpected scanner plugin")
24
+ require(document.get("plugin-uri") == "https://github.com/ossf/pvtr-github-repo-scanner",
25
+ "unexpected scanner source")
26
+ suites = document.get("evaluation-suites")
27
+ require(isinstance(suites, list) and len(suites) == 1, "expected one evaluation suite")
28
+ suite = suites[0]
29
+ require(isinstance(suite, dict), "suite must be an object")
30
+ require(suite.get("catalog-id") == CATALOG, "unexpected assessment catalog")
31
+ require(suite.get("name") == f"pvtr_{CATALOG}", "unexpected assessment suite")
32
+ require(suite.get("corrupted-state") is False, "assessment is incomplete or corrupted")
33
+ require(suite.get("result") in RESULTS, "invalid suite result")
34
+ evaluation_log = suite.get("control-evaluations")
35
+ require(isinstance(evaluation_log, dict), "missing structured control evaluations")
36
+ require(evaluation_log.get("metadata", {}).get("type") == "EvaluationLog",
37
+ "unexpected evaluation artifact type")
38
+ controls = evaluation_log.get("evaluations")
39
+ require(isinstance(controls, list) and controls, "no repository control results")
40
+ control_ids, requirement_ids, requirements = set(), set(), []
41
+ for control in controls:
42
+ require(isinstance(control, dict), "control must be an object")
43
+ ref = control.get("control", {})
44
+ control_id = ref.get("entry-id", "")
45
+ require(ref.get("reference-id") == CATALOG and
46
+ isinstance(control_id, str) and re.fullmatch(r"OSPS-[A-Z]{2}-\d{2}", control_id),
47
+ "invalid control reference")
48
+ require(control_id not in control_ids, "duplicate control result")
49
+ control_ids.add(control_id)
50
+ require(control.get("result") in RESULTS, "invalid control result")
51
+ logs = control.get("assessment-logs")
52
+ require(isinstance(logs, list) and logs, "control has no requirement results")
53
+ for log in logs:
54
+ require(isinstance(log, dict), "requirement must be an object")
55
+ ref = log.get("requirement", {})
56
+ requirement_id = ref.get("entry-id", "")
57
+ require(ref.get("reference-id") == CATALOG and isinstance(requirement_id, str) and
58
+ re.fullmatch(re.escape(control_id) + r"\.\d{2}", requirement_id),
59
+ "invalid requirement reference")
60
+ require(requirement_id not in requirement_ids, "duplicate requirement result")
61
+ requirement_ids.add(requirement_id)
62
+ require(log.get("result") in RESULTS, "invalid requirement result")
63
+ steps = log.get("steps-executed", 0)
64
+ require(type(steps) is int and steps >= 0, "invalid executed-step count")
65
+ if log["result"] not in ("Not Run", "Unknown"):
66
+ require(steps > 0, "requirement result has no executed assessment steps")
67
+ requirements.append(log)
68
+ executed = [log for log in requirements if log.get("steps-executed", 0) > 0
69
+ and log["result"] != "Not Run"]
70
+ require(executed, "no executed repository assessments")
71
+ # This requires observed repository data, not only GitHub-enforced defaults.
72
+ require(any(log["requirement"]["entry-id"] == "OSPS-QA-01.01" and
73
+ log["result"] == "Passed" for log in executed),
74
+ "scanner did not confirm the public repository was read")
75
+ return controls, requirements, executed
76
+
77
+
78
+ def summary(controls, requirements, executed):
79
+ lines = ["## OSPS Baseline collection", "", f"Catalog: `{CATALOG}` · Maturity Level 1", "",
80
+ "| Result | Controls | Requirements |", "|:--|--:|--:|"]
81
+ control_counts = collections.Counter(control["result"] for control in controls)
82
+ requirement_counts = collections.Counter(log["result"] for log in requirements)
83
+ lines += [f"| {result} | {control_counts[result]} | {requirement_counts[result]} |"
84
+ for result in RESULTS]
85
+ lines += ["", f"Validated {len(controls)} controls and {len(requirements)} requirements; "
86
+ f"{len(executed)} requirements have executed results.", "",
87
+ "Collection succeeded. This does not mean all controls passed. "
88
+ "Needs Review, Unknown and Not Run remain unresolved; the scanner's "
89
+ "'Possible' log count is not a pass count."]
90
+ findings = [log for log in requirements if log["result"] in ("Failed", "Needs Review", "Unknown")]
91
+ if findings:
92
+ lines += ["", "### Findings requiring follow-up", "", "| Requirement | Result |",
93
+ "|:--|:--|"]
94
+ lines += [f"| {log['requirement']['entry-id']} | {log['result']} |" for log in findings]
95
+ return "\n".join(lines) + "\n"
96
+
97
+
98
+ def main():
99
+ if len(sys.argv) != 2:
100
+ raise ValueError("usage: osps-results.py PATH_TO_PVTR_JSON")
101
+ document = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8"))
102
+ report = summary(*inspect_results(document))
103
+ print(report, end="")
104
+ if path := os.environ.get("GITHUB_STEP_SUMMARY"):
105
+ with pathlib.Path(path).open("a", encoding="utf-8") as stream:
106
+ stream.write(report)
107
+
108
+
109
+ if __name__ == "__main__":
110
+ try:
111
+ main()
112
+ except (OSError, ValueError, TypeError, AttributeError, KeyError) as error:
113
+ print(f"OSPS result validation failed: {error}", file=sys.stderr)
114
+ sys.exit(1)
@@ -9,7 +9,7 @@ REGISTRY="${BAILING_IMAGE_REGISTRY:-$DEFAULT_REGISTRY}"
9
9
  NAMESPACE="${BAILING_IMAGE_NAMESPACE:-$DEFAULT_NAMESPACE}"
10
10
  PACKAGE_VERSION="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' package.json | head -1)"
11
11
  TAG="${BAILING_IMAGE_TAG:-$PACKAGE_VERSION}"
12
- [ -n "$TAG" ] || TAG="0.8.0"
12
+ [ -n "$TAG" ] || TAG="0.9.1"
13
13
  NODE_IMAGE="${BAILING_NODE_IMAGE:-node:22-bookworm-slim}"
14
14
  PLATFORM="${BAILING_IMAGE_PLATFORM:-linux/amd64}"
15
15
  PUSH="${BAILING_PUSH_IMAGES:-0}"
@@ -39,6 +39,8 @@ const requiredRepoFiles = [
39
39
  'docs/RELEASE_NOTES_v0.5.1.md',
40
40
  'docs/RELEASE_NOTES_v0.7.0.md',
41
41
  'docs/RELEASE_NOTES_v0.8.0.md',
42
+ 'docs/RELEASE_NOTES_v0.9.0.md',
43
+ 'docs/RELEASE_NOTES_v0.9.1.md',
42
44
  'docs/RELEASE_NOTES_v0.6.1.md',
43
45
  'docs/RELEASE_NOTES_v0.6.0.md',
44
46
  'docs/CHANGELOG.md',
@@ -57,6 +57,12 @@ async function closeServer(server) {
57
57
  }
58
58
 
59
59
  console.log('— SDK runtime helpers');
60
+ const nodeUsage = run(process.execPath, ['--test', 'sdk/node/tests/usage.test.mjs']);
61
+ ok('Node billing issuer transport boundaries', nodeUsage.status === 0, nodeUsage.stderr || nodeUsage.stdout);
62
+ const phpUsage = run(process.env.BAILING_SDK_PHP7_BINARY || 'php', ['sdk/php7/tests/usage-client.php']);
63
+ ok('PHP7 billing issuer transport boundaries', phpUsage.status === 0, phpUsage.stderr || phpUsage.stdout);
64
+ const billingTypes = run(process.execPath, ['node_modules/typescript/bin/tsc', '--noEmit', '--strict', '--skipLibCheck', '--module', 'NodeNext', '--target', 'ES2022', '--types', 'node', 'sdk/node/tests/usage-types.mts']);
65
+ ok('Node billing public package types match the documented methods', billingTypes.status === 0, billingTypes.stderr || billingTypes.stdout);
60
66
  ok('Node signTicket deterministic vector', signTicket('secret', 'tenant:user', { expiresAt: 2_000_000_000 }) === expectedTicket);
61
67
 
62
68
  const ts = Math.floor(Date.now() / 1000);
@@ -0,0 +1,225 @@
1
+ // Local-only synthetic release acceptance. Never loads application configuration.
2
+ // Run: node --import tsx scripts/verify-billing-install-upgrade.mjs
3
+ // Requires an isolated MySQL at 127.0.0.1:16307 (root, empty password).
4
+ import assert from 'node:assert/strict';
5
+ import { execFileSync } from 'node:child_process';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+ import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises';
8
+ import { tmpdir } from 'node:os';
9
+ import { dirname, join } from 'node:path';
10
+ import { fileURLToPath, pathToFileURL } from 'node:url';
11
+ import { createConnection, createPool } from 'mysql2/promise';
12
+ import { migrateBailingHubCoreSchema } from '../src/infrastructure/schema/core-schema-migrator.ts';
13
+ import { UsageRepository } from '../src/modules/usage/repository.ts';
14
+ import { getUsageIdentity } from '../src/modules/usage/identity.ts';
15
+ import { getBillingRepository } from '../src/modules/usage/billing-repository.ts';
16
+
17
+ const root = fileURLToPath(new URL('../', import.meta.url));
18
+ const mysql = Object.freeze({ host: '127.0.0.1', port: 16307, user: 'root', password: '',
19
+ connectionLimit: 2, connectTimeout: 5_000, dateStrings: true,
20
+ supportBigNumbers: true, bigNumberStrings: true });
21
+ const expectedAdditions = ['063_usage_model_billing.sql', '064_period_plan_allowance.sql'];
22
+ const git = (...args) => execFileSync('git', args, { cwd: root, maxBuffer: 8 * 1024 * 1024 });
23
+ const digest = data => createHash('sha256').update(data).digest('hex');
24
+ const quote = identifier => { assert.match(identifier, /^[a-zA-Z0-9_]+$/); return `\`${identifier}\``; };
25
+ const canonical = value => {
26
+ if (Array.isArray(value)) return value.map(canonical);
27
+ if (value && typeof value === 'object') return Object.fromEntries(
28
+ Object.keys(value).sort().map(key => [key, canonical(value[key])]),
29
+ );
30
+ return value;
31
+ };
32
+
33
+ async function manifest(directory) {
34
+ const names = (await readdir(directory)).filter(name => name.endsWith('.sql')).sort();
35
+ return Promise.all(names.map(async filename => ({ filename,
36
+ checksum_sha256: digest(await readFile(join(directory, filename))) })));
37
+ }
38
+
39
+ async function stageBaseline(baselineRoot, revision) {
40
+ // Extract only the local public tag's SQL and official migrator dependencies.
41
+ const names = git('ls-tree', '-r', '--name-only', revision, 'sql', 'src/infrastructure/schema')
42
+ .toString().trim().split('\n').filter(name => name.endsWith('.sql')
43
+ || name.endsWith('.ts') && !name.endsWith('.test.ts'));
44
+ for (const name of names) {
45
+ const destination = join(baselineRoot, name);
46
+ await mkdir(dirname(destination), { recursive: true });
47
+ await writeFile(destination, git('show', `${revision}:${name}`));
48
+ }
49
+ await writeFile(join(baselineRoot, 'package.json'), '{"type":"module"}\n');
50
+ return import(pathToFileURL(join(baselineRoot, 'src/infrastructure/schema/core-schema-migrator.ts')).href);
51
+ }
52
+
53
+ async function tables(connection) {
54
+ const [rows] = await connection.query('SHOW FULL TABLES WHERE Table_type = ?', ['BASE TABLE']);
55
+ return rows.map(row => Object.values(row)[0]).sort();
56
+ }
57
+
58
+ async function snapshot(connection, names) {
59
+ const result = {};
60
+ for (const table of names) {
61
+ const [rows] = await connection.query(`SELECT * FROM ${quote(table)}`);
62
+ const [ddl] = await connection.query(`SHOW CREATE TABLE ${quote(table)}`);
63
+ const serialized = rows.map(row => JSON.stringify(canonical(row))).sort();
64
+ result[table] = { rowCount: rows.length, rowsSha256: digest(JSON.stringify(serialized)),
65
+ schemaSha256: digest(ddl[0]['Create Table']) };
66
+ }
67
+ return result;
68
+ }
69
+
70
+ async function verifyLedger(connection, expected) {
71
+ const [rows] = await connection.query(
72
+ 'SELECT filename, checksum_sha256 FROM bz_schema_migrations ORDER BY filename',
73
+ );
74
+ assert.deepEqual(rows.map(row => ({ ...row })), expected);
75
+ }
76
+
77
+ async function seedLegacyRecords(connection) {
78
+ const date = '2026-01-02 03:04:05', expires = '2036-01-02 03:04:05';
79
+ const session = randomUUID(), job = randomUUID(), authorization = randomUUID();
80
+ const client = 'synthetic-upgrade-client', route = 'synthetic-upgrade-route';
81
+ const principal = JSON.stringify({ tenant: 'synthetic', id: 'upgrade-user' });
82
+ const routes = JSON.stringify([route]);
83
+ const fixtures = [
84
+ ['bz_clients', { app_id: client, name: 'Synthetic existing integration', token: '0'.repeat(32),
85
+ allowed_routes: routes, created_at: date, updated_at: date }],
86
+ ['bz_routes', { route_key: route, name: 'Synthetic existing route', created_at: date, updated_at: date }],
87
+ ['bz_agent_sessions', { session_id: session, client_app_id: client, device_label: 'Synthetic device',
88
+ principal_json: principal, on_behalf_of: 'upgrade-user', allowed_routes: routes,
89
+ access_token_hash: '1'.repeat(64), access_expires_at: expires, refresh_expires_at: expires,
90
+ created_at: date, updated_at: date, subject_display: JSON.stringify({ name: 'Synthetic person' }) }],
91
+ ['bz_agent_authorizations', { authorization_id: authorization, client_app_id: client,
92
+ redirect_uri: 'http://127.0.0.1:1/synthetic-callback', state_value: 'synthetic-state',
93
+ requested_routes: routes, device_label: 'Synthetic device', code_challenge: 'x'.repeat(43),
94
+ status: 'consumed', principal_json: principal, on_behalf_of: 'upgrade-user', allowed_routes: routes,
95
+ session_id: session, created_at: date, expires_at: expires, consumed_at: date }],
96
+ ['bz_agent_refresh_tokens', { token_hash: '2'.repeat(64), session_id: session,
97
+ status: 'used', created_at: date, expires_at: expires, used_at: date }],
98
+ ['bz_jobs', { job_id: job, request_id: 'synthetic-original-request', profile: 'readonly',
99
+ status: 'done', client_app_id: client, agent_session_id: session, on_behalf_of: 'upgrade-user',
100
+ result: JSON.stringify({ text: 'Original synthetic result' }), created_at: date, updated_at: date }],
101
+ ['bz_audit', { ts: date, job_id: job, request_id: 'synthetic-original-request', event: 'finished',
102
+ detail: JSON.stringify({ preserved: true, fixture: 'upgrade' }) }],
103
+ ['bz_approvals', { job_id: job, action: JSON.stringify({ synthetic: true }), status: 'approved',
104
+ decided_by: 'synthetic-reviewer', created_at: date, decided_at: date }],
105
+ ];
106
+ for (const [table, record] of fixtures) await connection.query('INSERT INTO ?? SET ?', [table, record]);
107
+ return fixtures.map(([table]) => table);
108
+ }
109
+
110
+ async function verifyOptionalBilling(connection, database) {
111
+ const usageTables = (await tables(connection)).filter(table => table.startsWith('bz_usage_'));
112
+ assert.equal(usageTables.length, 14);
113
+ const before = await snapshot(connection, usageTables);
114
+ for (const [table, value] of Object.entries(before)) assert.equal(value.rowCount, 0, `${table} must be empty`);
115
+ const pool = createPool({ ...mysql, database });
116
+ try {
117
+ const repository = new UsageRepository(() => pool);
118
+ assert.equal(await getUsageIdentity(repository).ready(), true);
119
+ assert.equal(await getBillingRepository(repository).ready(), true);
120
+ assert.deepEqual(await getBillingRepository(repository).listPlans(), []);
121
+ } finally { await pool.end(); }
122
+ assert.deepEqual(await snapshot(connection, usageTables), before,
123
+ 'Readiness and listing must not create identities, plans, grants, requests or charges');
124
+ return { tables: usageTables.length, allEmpty: true, schemaReady: true, autoProvisioned: false };
125
+ }
126
+
127
+ function assertNoReplay(result, expectedFiles) {
128
+ assert.deepEqual(result.appliedFiles, []);
129
+ assert.deepEqual(result.skippedFiles, expectedFiles);
130
+ assert.deepEqual(result.checksumBackfilledFiles, []);
131
+ assert.equal(result.executedStatements, 0);
132
+ assert.equal(result.toleratedStatements, 0);
133
+ }
134
+
135
+ const baselineRoot = await mkdtemp(join(tmpdir(), 'bailing-billing-upgrade-'));
136
+ let admin;
137
+ const createdDatabases = new Set();
138
+ async function isolatedDatabase(label, callback) {
139
+ const database = `billing_install_${label}_${randomUUID().replaceAll('-', '')}`;
140
+ assert.match(database, /^billing_install_(fresh|upgrade)_[a-f0-9]{32}$/);
141
+ await admin.query(`CREATE DATABASE ${quote(database)} CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
142
+ createdDatabases.add(database);
143
+ let connection;
144
+ try {
145
+ connection = await createConnection({ ...mysql, database });
146
+ return await callback(connection, database);
147
+ } finally {
148
+ if (connection) await connection.end();
149
+ await admin.query(`DROP DATABASE ${quote(database)}`);
150
+ createdDatabases.delete(database);
151
+ }
152
+ }
153
+
154
+ try {
155
+ const baselineRevision = git('rev-parse', 'v0.8.0^{commit}').toString().trim();
156
+ const candidateHead = git('rev-parse', 'HEAD').toString().trim();
157
+ const { migrateBailingHubCoreSchema: migrateBaseline } = await stageBaseline(baselineRoot, baselineRevision);
158
+ const baselineManifest = await manifest(join(baselineRoot, 'sql'));
159
+ const currentManifest = await manifest(join(root, 'sql'));
160
+ const baselineNames = baselineManifest.map(file => file.filename);
161
+ const currentNames = currentManifest.map(file => file.filename);
162
+ assert.deepEqual(currentNames.filter(name => !baselineNames.includes(name)), expectedAdditions);
163
+ for (const oldFile of baselineManifest) assert.deepEqual(
164
+ currentManifest.find(file => file.filename === oldFile.filename), oldFile,
165
+ `Published migration ${oldFile.filename} must remain byte-identical`,
166
+ );
167
+ admin = await createConnection(mysql);
168
+ const [[server]] = await admin.query('SELECT VERSION() AS version');
169
+ const fresh = await isolatedDatabase('fresh', async (connection, database) => {
170
+ const input = { mysql: { ...mysql, database }, connection };
171
+ assert.deepEqual(await tables(connection), []);
172
+ const install = await migrateBailingHubCoreSchema(input);
173
+ assert.deepEqual(install.appliedFiles, currentNames);
174
+ assert.deepEqual(install.skippedFiles, []);
175
+ await verifyLedger(connection, currentManifest);
176
+ const billing = await verifyOptionalBilling(connection, database);
177
+ const before = await snapshot(connection, await tables(connection));
178
+ const rerun = await migrateBailingHubCoreSchema(input);
179
+ assertNoReplay(rerun, currentNames);
180
+ assert.deepEqual(await snapshot(connection, await tables(connection)), before);
181
+ return { migrations: install.appliedFiles.length, executedStatements: install.executedStatements,
182
+ toleratedStatements: install.toleratedStatements, tables: Object.keys(before).length,
183
+ rerunExecutedStatements: rerun.executedStatements, billing };
184
+ });
185
+ const upgrade = await isolatedDatabase('upgrade', async (connection, database) => {
186
+ const input = { mysql: { ...mysql, database }, connection };
187
+ const initial = await migrateBaseline(input);
188
+ assert.deepEqual(initial.appliedFiles, baselineNames);
189
+ await verifyLedger(connection, baselineManifest);
190
+ assert.equal((await tables(connection)).some(table => table.startsWith('bz_usage_')), false);
191
+ const seededTables = await seedLegacyRecords(connection);
192
+ const legacyTables = (await tables(connection)).filter(table => table !== 'bz_schema_migrations');
193
+ const before = await snapshot(connection, legacyTables);
194
+ const [oldLedger] = await connection.query('SELECT * FROM bz_schema_migrations ORDER BY filename');
195
+ const migrated = await migrateBailingHubCoreSchema(input);
196
+ assert.deepEqual(migrated.appliedFiles, expectedAdditions);
197
+ assert.deepEqual(migrated.skippedFiles, baselineNames);
198
+ assert.deepEqual(migrated.checksumBackfilledFiles, []);
199
+ await verifyLedger(connection, currentManifest);
200
+ const [newLedger] = await connection.query('SELECT * FROM bz_schema_migrations ORDER BY filename');
201
+ assert.deepEqual(newLedger.filter(row => baselineNames.includes(row.filename)), oldLedger);
202
+ assert.deepEqual(await snapshot(connection, legacyTables), before,
203
+ 'Every original table schema and row must be preserved');
204
+ const billing = await verifyOptionalBilling(connection, database);
205
+ const complete = await snapshot(connection, await tables(connection));
206
+ const rerun = await migrateBailingHubCoreSchema(input);
207
+ assertNoReplay(rerun, currentNames);
208
+ assert.deepEqual(await snapshot(connection, await tables(connection)), complete);
209
+ return { baselineMigrations: initial.appliedFiles.length, appliedMigrations: migrated.appliedFiles,
210
+ executedStatements: migrated.executedStatements, preservedTables: legacyTables.length,
211
+ preservedRows: Object.values(before).reduce((total, value) => total + value.rowCount, 0),
212
+ seededTables, originalLedgerPreserved: true, oldSchemaAndDataPreserved: true,
213
+ rerunExecutedStatements: rerun.executedStatements, billing };
214
+ });
215
+ console.log(JSON.stringify({ status: 'passed', baselineRevision, candidateHead, mysqlVersion: server.version,
216
+ publishedSqlUnchanged: true, baselineSqlManifestSha256: digest(JSON.stringify(baselineManifest)),
217
+ currentSqlManifestSha256: digest(JSON.stringify(currentManifest)), fresh, upgrade,
218
+ syntheticDatabasesRemoved: createdDatabases.size === 0 }, null, 2));
219
+ } finally {
220
+ if (admin) {
221
+ for (const database of createdDatabases) await admin.query(`DROP DATABASE ${quote(database)}`);
222
+ await admin.end();
223
+ }
224
+ await rm(baselineRoot, { recursive: true, force: true });
225
+ }
@@ -131,6 +131,8 @@ const requiredFiles = [
131
131
  'docs/RELEASE_NOTES_v0.5.1.md',
132
132
  'docs/RELEASE_NOTES_v0.7.0.md',
133
133
  'docs/RELEASE_NOTES_v0.8.0.md',
134
+ 'docs/RELEASE_NOTES_v0.9.0.md',
135
+ 'docs/RELEASE_NOTES_v0.9.1.md',
134
136
  'docs/RELEASE_NOTES_v0.6.1.md',
135
137
  'docs/RELEASE_NOTES_v0.6.0.md',
136
138
  'docs/CHANGELOG.md',
@@ -105,3 +105,20 @@ const job = await hub.run({
105
105
  const result = await hub.getJob(job.job_id);
106
106
  await hub.send({ requestId: `notice_${orderId}`, channel: 'team-im', to: 'user_001', text: '任务已完成' });
107
107
  ```
108
+
109
+ ## 可选模型套餐与登录
110
+
111
+ `UsageIssuerClient` 使用独立的服务端 Usage issuer 凭据,提供 `exchangeSession`、`revokeUser`、`listBillingPlans`、`getBillingSummary`、`grantBillingPlan` 和 `controlBillingPlan`。不要复用业务 Client Token,也不要把 issuer 凭据或管理方法交给浏览器或模型。
112
+
113
+ 业务后端根据已验证登录提交 `request_key/tenant/subject/generation/service_id` 换取短期模型凭证。`model_access: "service"` 限定所选模型;显式 `"token_gateway"` 可在身份来源及套餐允许的模型交集中选择,不扩大业务权限。只将短期凭证和固定身份交给对应使用人。登录不依赖套餐摘要成功;未开通套餐通过摘要的 `grant=null` 表达。
114
+
115
+ `grantBillingPlan(accountId, input)` 的 input 包含原 `request_key`、`plan_id`、`expected_revision`。`controlBillingPlan(accountId, input)` 使用原请求键、当前修订和 `state: active|suspended`。`getBillingSummary(accountId)` 读取当前账户美元余额、实际费用与周期状态,不执行模型。向用户展示时只使用摘要 `presentation`:额度包显示积分,周期套餐显示剩余百分比;美元字段用于计费核账;原始 Token 用量保留在模型请求明细中。售价、收款和合同由业务系统负责。
116
+
117
+ 套餐管理统一使用 `/usage/v1/external/billing/`。套餐目录返回 `config.priceUsd`、周期套餐必填的 `config.periodAllowanceUsd`、`periodUnit`、`duration`、`serviceIds` 和 `multiplier`。周期套餐售价与每周期额度是两个独立字段;账户摘要使用 `bailing.billing-summary.v1`,美元余额为 `availableUsd`,已消费为 `consumedUsd`,客户展示使用 `presentation`。
118
+
119
+ 管理写入不会自动重试。回包丢失时沿原键、原参数核对,不能换新键重复发放。异常只包含脱敏错误码、`outcome`、`requestKey` 和安全反馈。`revokeUser` 按原 tenant/subject/generation 幂等停用,不需要 request_key。
120
+
121
+ 完整契约见 [模型服务与套餐计费](../../docs/MODEL_BILLING.md)。安装业务 SDK 本身不接管本地模型流量;客户端接入模型请求/流式入口后才会计量。
122
+
123
+
124
+ 示例将准备和发送分开:先调用 `prepareBillingPlan` 并持久化 `grantInput`,再调用 `applyBillingPlan`;回包不确定时沿用已保存的输入,不能重新计算修订。服务端开通示例见 [examples/billing.mjs](examples/billing.mjs)。TypeScript 可通过 `import { UsageIssuerClient, type BillingSummary } from "@bailinghub/connect/usage"` 获取完整的套餐与身份类型。
@@ -0,0 +1,21 @@
1
+ import { UsageIssuerClient } from '../src/usage.mjs';
2
+
3
+ /** Invoke after authenticating a user in your own backend. No network call occurs on import. */
4
+ export async function prepareBillingPlan({ baseUrl, issuerToken, identity, loginRequestKey, serviceId, planId, orderRequestKey }) {
5
+ const issuer = new UsageIssuerClient({ baseUrl, issuerToken });
6
+ const login = await issuer.exchangeSession({
7
+ ...identity, request_key: loginRequestKey, service_id: serviceId, model_access: 'token_gateway',
8
+ });
9
+ const accountId = login.session.accountId;
10
+ const summary = await issuer.getBillingSummary(accountId);
11
+ // Persist this exact body with your order before calling grantBillingPlan.
12
+ const grantInput = { request_key: orderRequestKey, plan_id: planId, expected_revision: summary.grant?.revision ?? 0 };
13
+ return { credential: login.credential, session: login.session, accountId, grantInput };
14
+ }
15
+
16
+ /** Submit the saved input, including its original revision. Do not prepare it again on retry. */
17
+ export async function applyBillingPlan({ baseUrl, issuerToken, accountId, grantInput }) {
18
+ const issuer = new UsageIssuerClient({ baseUrl, issuerToken });
19
+ await issuer.grantBillingPlan(accountId, grantInput);
20
+ return (await issuer.getBillingSummary(accountId)).presentation;
21
+ }
@@ -5,7 +5,11 @@
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
7
7
  "exports": {
8
- ".": "./src/index.mjs"
8
+ ".": "./src/index.mjs",
9
+ "./usage": {
10
+ "types": "./src/usage.d.mts",
11
+ "default": "./src/usage.mjs"
12
+ }
9
13
  },
10
14
  "files": [
11
15
  "src",
@@ -248,3 +248,5 @@ export class HubClient {
248
248
  }
249
249
  }
250
250
  }
251
+
252
+ export { UsageIssuerClient, UsageIssuerError } from './usage.mjs';