@booki-aui/core 0.2.1 → 0.3.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/CHANGELOG.md +16 -0
- package/dist/activity.js +2 -2
- package/dist/aging.js +2 -2
- package/dist/approval.js +2 -2
- package/dist/attachments.js +2 -2
- package/dist/audit.js +2 -2
- package/dist/{chunk-2H3DAON4.js → chunk-2HIQCBZT.js} +2 -2
- package/dist/{chunk-4OAXKS34.js → chunk-33O2OHL6.js} +2 -2
- package/dist/{chunk-OUWAGY5G.js → chunk-4F5QLWKQ.js} +4 -4
- package/dist/{chunk-5MYAIV42.js → chunk-5ELWBE73.js} +13 -3
- package/dist/{chunk-5MYAIV42.js.map → chunk-5ELWBE73.js.map} +1 -1
- package/dist/{chunk-3WGVKVPL.js → chunk-64OXR7M2.js} +2 -2
- package/dist/{chunk-O7PLFRE7.js → chunk-A2QYZDOI.js} +2 -2
- package/dist/{chunk-5Z6LU5LH.js → chunk-AK5V6MNR.js} +2 -2
- package/dist/{chunk-HWGE4OOL.js → chunk-DT3HAYKU.js} +3 -3
- package/dist/{chunk-AGNXTHJA.js → chunk-FWZPV7NF.js} +2 -2
- package/dist/{chunk-I4YPEKDY.js → chunk-GGK3KTR6.js} +2 -2
- package/dist/{chunk-LJAY7P3Q.js → chunk-GH6FRLYM.js} +2 -2
- package/dist/{chunk-ROCF6IEK.js → chunk-GSDFDZPH.js} +2 -2
- package/dist/{chunk-6BK7VPNH.js → chunk-HCJY7UL5.js} +3 -3
- package/dist/{chunk-CUKV2KU3.js → chunk-HTILL5EQ.js} +2 -2
- package/dist/{chunk-QUMUL4OH.js → chunk-I5SGNZIS.js} +2 -2
- package/dist/{chunk-U5T5SUPP.js → chunk-J3LLJEU2.js} +9 -1
- package/dist/{chunk-U5T5SUPP.js.map → chunk-J3LLJEU2.js.map} +1 -1
- package/dist/{chunk-N77E7ZP7.js → chunk-LR4X7GTZ.js} +2 -2
- package/dist/{chunk-MV3NCGG4.js → chunk-LVKCG5WR.js} +3 -3
- package/dist/{chunk-BMSGD3FU.js → chunk-PG6CC27E.js} +2 -2
- package/dist/{chunk-XXMOQEIG.js → chunk-PL2ZRRTV.js} +2 -2
- package/dist/{chunk-JQFQM2K3.js → chunk-PLYGQ63I.js} +2 -2
- package/dist/{chunk-4ONDQS7Q.js → chunk-SBWIM62T.js} +2 -2
- package/dist/{chunk-EGSWMJ7L.js → chunk-SPA45TN5.js} +2 -2
- package/dist/{chunk-DJPVY5F2.js → chunk-TYL4PAUC.js} +2 -2
- package/dist/{chunk-V37IQ36D.js → chunk-UFGTZK2J.js} +2 -2
- package/dist/{chunk-JIYWHAO3.js → chunk-VMDKFRLL.js} +2 -2
- package/dist/{chunk-NY6TSOQO.js → chunk-XSBPSQMB.js} +2 -2
- package/dist/{chunk-T3M424SP.js → chunk-YGHY2MVR.js} +3 -3
- package/dist/{chunk-FP52SC7S.js → chunk-YUPCBRRP.js} +2 -2
- package/dist/{chunk-3PAJMQ5H.js → chunk-ZFWPR3SQ.js} +3 -3
- package/dist/client-request.js +2 -2
- package/dist/close.js +2 -2
- package/dist/document-signoff.js +2 -2
- package/dist/expense.js +2 -2
- package/dist/findings.js +2 -2
- package/dist/fixed-assets.js +3 -3
- package/dist/funnel.js +2 -2
- package/dist/fx.js +3 -3
- package/dist/index.js +30 -30
- package/dist/invoice.js +2 -2
- package/dist/ledger.js +3 -3
- package/dist/locale/index.js +2 -2
- package/dist/messages.js +2 -2
- package/dist/money.js +2 -2
- package/dist/msg.d.ts +8 -0
- package/dist/msg.js +1 -1
- package/dist/payment-batch.js +2 -2
- package/dist/period-lock.js +3 -3
- package/dist/period.js +2 -2
- package/dist/permissions.js +2 -2
- package/dist/pipeline.js +2 -2
- package/dist/reconciliation.js +2 -2
- package/dist/recurring.js +2 -2
- package/dist/server.d.ts +8 -2
- package/dist/server.js +17 -17
- package/dist/server.js.map +1 -1
- package/dist/supplier-invoice.js +2 -2
- package/dist/table.js +2 -2
- package/dist/vat-return.js +3 -3
- package/dist/voucher.js +6 -6
- package/package.json +1 -1
- /package/dist/{chunk-2H3DAON4.js.map → chunk-2HIQCBZT.js.map} +0 -0
- /package/dist/{chunk-4OAXKS34.js.map → chunk-33O2OHL6.js.map} +0 -0
- /package/dist/{chunk-OUWAGY5G.js.map → chunk-4F5QLWKQ.js.map} +0 -0
- /package/dist/{chunk-3WGVKVPL.js.map → chunk-64OXR7M2.js.map} +0 -0
- /package/dist/{chunk-O7PLFRE7.js.map → chunk-A2QYZDOI.js.map} +0 -0
- /package/dist/{chunk-5Z6LU5LH.js.map → chunk-AK5V6MNR.js.map} +0 -0
- /package/dist/{chunk-HWGE4OOL.js.map → chunk-DT3HAYKU.js.map} +0 -0
- /package/dist/{chunk-AGNXTHJA.js.map → chunk-FWZPV7NF.js.map} +0 -0
- /package/dist/{chunk-I4YPEKDY.js.map → chunk-GGK3KTR6.js.map} +0 -0
- /package/dist/{chunk-LJAY7P3Q.js.map → chunk-GH6FRLYM.js.map} +0 -0
- /package/dist/{chunk-ROCF6IEK.js.map → chunk-GSDFDZPH.js.map} +0 -0
- /package/dist/{chunk-6BK7VPNH.js.map → chunk-HCJY7UL5.js.map} +0 -0
- /package/dist/{chunk-CUKV2KU3.js.map → chunk-HTILL5EQ.js.map} +0 -0
- /package/dist/{chunk-QUMUL4OH.js.map → chunk-I5SGNZIS.js.map} +0 -0
- /package/dist/{chunk-N77E7ZP7.js.map → chunk-LR4X7GTZ.js.map} +0 -0
- /package/dist/{chunk-MV3NCGG4.js.map → chunk-LVKCG5WR.js.map} +0 -0
- /package/dist/{chunk-BMSGD3FU.js.map → chunk-PG6CC27E.js.map} +0 -0
- /package/dist/{chunk-XXMOQEIG.js.map → chunk-PL2ZRRTV.js.map} +0 -0
- /package/dist/{chunk-JQFQM2K3.js.map → chunk-PLYGQ63I.js.map} +0 -0
- /package/dist/{chunk-4ONDQS7Q.js.map → chunk-SBWIM62T.js.map} +0 -0
- /package/dist/{chunk-EGSWMJ7L.js.map → chunk-SPA45TN5.js.map} +0 -0
- /package/dist/{chunk-DJPVY5F2.js.map → chunk-TYL4PAUC.js.map} +0 -0
- /package/dist/{chunk-V37IQ36D.js.map → chunk-UFGTZK2J.js.map} +0 -0
- /package/dist/{chunk-JIYWHAO3.js.map → chunk-VMDKFRLL.js.map} +0 -0
- /package/dist/{chunk-NY6TSOQO.js.map → chunk-XSBPSQMB.js.map} +0 -0
- /package/dist/{chunk-T3M424SP.js.map → chunk-YGHY2MVR.js.map} +0 -0
- /package/dist/{chunk-FP52SC7S.js.map → chunk-YUPCBRRP.js.map} +0 -0
- /package/dist/{chunk-3PAJMQ5H.js.map → chunk-ZFWPR3SQ.js.map} +0 -0
package/dist/recurring.js
CHANGED
|
@@ -11,8 +11,8 @@ import {
|
|
|
11
11
|
recurringBridge,
|
|
12
12
|
recurringCurrencies,
|
|
13
13
|
recurringIssues
|
|
14
|
-
} from "./chunk-
|
|
15
|
-
import "./chunk-
|
|
14
|
+
} from "./chunk-VMDKFRLL.js";
|
|
15
|
+
import "./chunk-J3LLJEU2.js";
|
|
16
16
|
export {
|
|
17
17
|
RECURRING_INTERVALS,
|
|
18
18
|
RECURRING_MOVEMENTS,
|
package/dist/server.d.ts
CHANGED
|
@@ -270,7 +270,13 @@ declare function guardSubmitVatReturn(context: GuardContext, input: {
|
|
|
270
270
|
*/
|
|
271
271
|
declare function toHttp<T>(verdict: Verdict<T>): {
|
|
272
272
|
status: number;
|
|
273
|
-
body:
|
|
273
|
+
body: HttpBody<T>;
|
|
274
274
|
};
|
|
275
|
+
/** What `toHttp` answers with: the value on success, `{ ok: false, code, message, issues? }` on a refusal. */
|
|
276
|
+
type HttpBody<T> = {
|
|
277
|
+
ok: true;
|
|
278
|
+
actor: string;
|
|
279
|
+
value: T;
|
|
280
|
+
} | Omit<Refusal, "status">;
|
|
275
281
|
|
|
276
|
-
export { type Advice, type AgentClaims, type AgentGrant, type GuardContext, PERSON_ONLY, type Refusal, RuleRefusal, type ServerActor, type Verdict, actorDeed, actorLabel, actorRecord, advise, guard, guardApproved, guardCloseDeal, guardClosePeriod, guardConfirmFinding, guardDecideApproval, guardFinalizeInvoice, guardPostVoucher, guardReleasePayments, guardSignDocument, guardSubmitVatReturn, issueAgentToken, toHttp, verifyAgentToken };
|
|
282
|
+
export { type Advice, type AgentClaims, type AgentGrant, type GuardContext, type HttpBody, PERSON_ONLY, type Refusal, RuleRefusal, type ServerActor, type Verdict, actorDeed, actorLabel, actorRecord, advise, guard, guardApproved, guardCloseDeal, guardClosePeriod, guardConfirmFinding, guardDecideApproval, guardFinalizeInvoice, guardPostVoucher, guardReleasePayments, guardSignDocument, guardSubmitVatReturn, issueAgentToken, toHttp, verifyAgentToken };
|
package/dist/server.js
CHANGED
|
@@ -1,54 +1,54 @@
|
|
|
1
1
|
import {
|
|
2
2
|
assertVatReturnReady
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-HCJY7UL5.js";
|
|
4
4
|
import {
|
|
5
5
|
assertPostable
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-4F5QLWKQ.js";
|
|
7
7
|
import {
|
|
8
8
|
releaseBatch
|
|
9
|
-
} from "./chunk-
|
|
10
|
-
import "./chunk-
|
|
9
|
+
} from "./chunk-AK5V6MNR.js";
|
|
10
|
+
import "./chunk-YGHY2MVR.js";
|
|
11
11
|
import {
|
|
12
12
|
DutyRefusal,
|
|
13
13
|
STANDARD_DUTY_RULES,
|
|
14
14
|
STANDARD_ROLES,
|
|
15
15
|
assertCan,
|
|
16
16
|
can
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-SBWIM62T.js";
|
|
18
18
|
import {
|
|
19
19
|
closeDeal
|
|
20
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-GH6FRLYM.js";
|
|
21
21
|
import {
|
|
22
22
|
finalizeInvoice
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-UFGTZK2J.js";
|
|
24
24
|
import {
|
|
25
25
|
isIsoDate
|
|
26
26
|
} from "./chunk-ICBA5A2V.js";
|
|
27
27
|
import {
|
|
28
28
|
localize,
|
|
29
29
|
msgIn
|
|
30
|
-
} from "./chunk-
|
|
30
|
+
} from "./chunk-5ELWBE73.js";
|
|
31
31
|
import {
|
|
32
32
|
signDocument
|
|
33
|
-
} from "./chunk-
|
|
33
|
+
} from "./chunk-A2QYZDOI.js";
|
|
34
34
|
import {
|
|
35
35
|
confirmFinding
|
|
36
|
-
} from "./chunk-
|
|
37
|
-
import "./chunk-
|
|
38
|
-
import "./chunk-
|
|
39
|
-
import "./chunk-
|
|
36
|
+
} from "./chunk-FWZPV7NF.js";
|
|
37
|
+
import "./chunk-PLYGQ63I.js";
|
|
38
|
+
import "./chunk-DT3HAYKU.js";
|
|
39
|
+
import "./chunk-TYL4PAUC.js";
|
|
40
40
|
import {
|
|
41
41
|
assertApproved,
|
|
42
42
|
decide
|
|
43
|
-
} from "./chunk-
|
|
43
|
+
} from "./chunk-2HIQCBZT.js";
|
|
44
44
|
import {
|
|
45
45
|
assertReadyToClose
|
|
46
|
-
} from "./chunk-
|
|
46
|
+
} from "./chunk-SPA45TN5.js";
|
|
47
47
|
import {
|
|
48
48
|
BookiError,
|
|
49
49
|
isBookiError,
|
|
50
50
|
msg
|
|
51
|
-
} from "./chunk-
|
|
51
|
+
} from "./chunk-J3LLJEU2.js";
|
|
52
52
|
import "./chunk-ZJXNLPER.js";
|
|
53
53
|
|
|
54
54
|
// src/agent-token.ts
|
|
@@ -225,7 +225,7 @@ function admit(context, permission) {
|
|
|
225
225
|
}
|
|
226
226
|
const personOnly = PERSON_ONLY.includes(permission) || (context.personOnly ?? []).includes(permission);
|
|
227
227
|
if (actor?.kind === "agent" && personOnly) {
|
|
228
|
-
const able = roles.filter((role) => role.permissions.includes(permission)).map((role) => role.name);
|
|
228
|
+
const able = roles.filter((role) => role.permissions.includes(permission) && !actor.roles.includes(role.id)).map((role) => role.name);
|
|
229
229
|
throw new BookiError("server.person-only", {
|
|
230
230
|
permission: String(permission),
|
|
231
231
|
roles: able.join(", ") || msg("permissions.none-defined")
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent-token.ts","../src/server.ts"],"sourcesContent":["/**\n * A short-lived credential of the agent's own, so the server can tell the\n * agent from the person it works for. Your sign-in issues it for a signed-in\n * person; the page sends it with the agent's writes; the server verifies it\n * and adds the agent's roles. Signed with HMAC-SHA-256 through WebCrypto, so\n * it runs in Node, edge runtimes, Deno and Bun.\n *\n * It is not a session: keep the person's own sign-in for their writes.\n */\n\nexport type AgentGrant = {\n /** The agent's id, as `actorLabel` writes it after `agent:`. */\n agentId: string;\n /** The person whose session the agent works in. */\n onBehalfOf: string;\n /** The client it came through (your page, an MCP client). */\n clientId?: string;\n /**\n * What the token is for: an engagement, a company, one API. `verifyAgentToken`\n * with `{ audience }` refuses a token issued for anything else.\n */\n audience?: string;\n /** Seconds it is valid. Default 900 (15 minutes), at most 86 400. */\n ttlSeconds?: number;\n};\n\n/** What a valid token says: add `roles` from your own records to make a `ServerActor`. */\nexport type AgentClaims = {\n id: string;\n kind: \"agent\";\n onBehalfOf: string;\n clientId?: string;\n audience?: string;\n /** This token's own id, for the audit trail (`actorRecord`). */\n grantId: string;\n /** When it stops being valid, in milliseconds since 1970. */\n expiresAt: number;\n};\n\nimport { BookiError } from \"./msg.js\";\n\nconst PREFIX = \"bk1\";\nconst encoder = new TextEncoder();\n\nconst base64url = (bytes: Uint8Array) =>\n btoa(String.fromCharCode(...bytes))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\nconst fromBase64url = (text: string) => {\n const plain = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(plain, (char) => char.charCodeAt(0));\n};\n\nasync function keyFor(secret: string): Promise<CryptoKey> {\n if (typeof secret !== \"string\" || secret.length < 32) {\n throw new BookiError(\"agent-token.secret-short\");\n }\n return crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n \"verify\",\n ]);\n}\n\n/** Issues a token for an agent working for `onBehalfOf`. Call it only for a person your sign-in established. */\nexport async function issueAgentToken(grant: AgentGrant, secret: string, now = Date.now()): Promise<string> {\n const ttl = grant.ttlSeconds ?? 900;\n if (!Number.isSafeInteger(ttl) || ttl < 1 || ttl > 86_400) {\n throw new BookiError(\"agent-token.ttl\", { value: String(ttl) });\n }\n if (!grant.agentId || !grant.onBehalfOf) throw new BookiError(\"agent-token.grant\");\n const claims: AgentClaims = {\n id: grant.agentId,\n kind: \"agent\",\n onBehalfOf: grant.onBehalfOf,\n ...(grant.clientId ? { clientId: grant.clientId } : {}),\n ...(grant.audience ? { audience: grant.audience } : {}),\n grantId: base64url(crypto.getRandomValues(new Uint8Array(12))),\n expiresAt: now + ttl * 1000,\n };\n const payload = base64url(encoder.encode(JSON.stringify(claims)));\n const signature = await crypto.subtle.sign(\"HMAC\", await keyFor(secret), encoder.encode(`${PREFIX}.${payload}`));\n return `${PREFIX}.${payload}.${base64url(new Uint8Array(signature))}`;\n}\n\n/**\n * The claims of a valid, unexpired token signed with `secret`, or null. Null\n * for every failure alike: a caller learns nothing about why.\n */\nexport async function verifyAgentToken(\n token: unknown,\n secret: string,\n now: number | { now?: number; audience?: string } = Date.now(),\n): Promise<AgentClaims | null> {\n const at = typeof now === \"number\" ? now : (now.now ?? Date.now());\n const audience = typeof now === \"number\" ? undefined : now.audience;\n const key = await keyFor(secret);\n if (typeof token !== \"string\" || token.length > 4096) return null;\n const [prefix, payload, signature, ...rest] = token.split(\".\");\n if (prefix !== PREFIX || !payload || !signature || rest.length) return null;\n try {\n const ok = await crypto.subtle.verify(\n \"HMAC\",\n key,\n fromBase64url(signature),\n encoder.encode(`${PREFIX}.${payload}`),\n );\n if (!ok) return null;\n const claims = JSON.parse(new TextDecoder().decode(fromBase64url(payload))) as AgentClaims;\n if (claims.kind !== \"agent\" || typeof claims.id !== \"string\" || typeof claims.onBehalfOf !== \"string\") return null;\n if (!Number.isFinite(claims.expiresAt) || claims.expiresAt <= at) return null;\n // Given an audience, only a token issued for exactly that one passes.\n if (audience !== undefined && claims.audience !== audience) return null;\n return claims;\n } catch {\n return null;\n }\n}\n","/**\n * The same rules the screen enforces, for your API.\n *\n * The controls refuse what a role may not do and what the books do not allow,\n * but a browser is not a security boundary: anything can call your API. Run\n * every write through one of these guards on the server, with the actor your\n * own sign-in established (never one the request says it is). Each guard\n * answers with a verdict you can send straight back: the HTTP status, a stable\n * code and the same sentence the control showed, in English or Norwegian.\n *\n * Order of checks, for every action:\n * 1. Signed in? 401\n * 2. A person's decision, and the actor an agent? 403\n * 3. Role allows it, in this entity? 403\n * And, for an agent acting for someone, theirs? 403 (with `personOf`)\n * 4. Separation of duties against what they did? 403\n * 5. A reason given, where one is required? 422\n * 6. The books allow it (balance, period, approvals, readiness)? 409 or 422\n *\n * Where the books are a matter of professional judgment (an audit file, say),\n * use `advise` instead of `guard`: steps 1 to 5 still refuse, and step 6 comes\n * back as warnings for the person to weigh.\n *\n * Framework-free: plain data in, plain data out. Works in Node, edge runtimes,\n * Deno and Bun.\n */\nexport { type AgentClaims, type AgentGrant, issueAgentToken, verifyAgentToken } from \"./agent-token.js\";\nimport { assertApproved, decide, type ApprovalDecision, type ApprovalLevel, type ApprovalRequest } from \"./approval.js\";\nimport { assertReadyToClose, type CloseSummary, type CloseTask } from \"./close.js\";\nimport { signDocument, type SignableDocument, type SignoffLevel, type SignoffRules } from \"./document-signoff.js\";\nimport { confirmFinding, type Finding } from \"./findings.js\";\nimport { finalizeInvoice, type Invoice } from \"./invoice.js\";\nimport { isIsoDate } from \"./iso-date.js\";\nimport { localize, msgIn, type MessageLanguage } from \"./messages.js\";\nimport { BookiError, isBookiError, msg } from \"./msg.js\";\nimport { releaseBatch, type PaymentBatch } from \"./payment-batch.js\";\nimport { closeDeal, type Deal, type DealOutcome, type PipelineStage } from \"./pipeline.js\";\nimport {\n STANDARD_DUTY_RULES,\n STANDARD_ROLES,\n DutyRefusal,\n assertCan,\n can,\n type Actor,\n type Deed,\n type DutyRule,\n type Permission,\n type Role,\n} from \"./permissions.js\";\nimport { assertVatReturnReady, type VatReturnComputation } from \"./vat-return.js\";\nimport { assertPostable, type VoucherBalance, type VoucherLine, type VoucherRules } from \"./voucher.js\";\n\n/**\n * Who is calling, as your sign-in established it. An agent gets its own\n * credential and comes here as `kind: \"agent\"`; `onBehalfOf` is the person\n * whose session started it. It is recorded, the duty rules count it, and with\n * `personOf` in the context the person's own roles limit what the agent may do.\n */\nexport type ServerActor = Actor & {\n kind: \"person\" | \"agent\";\n onBehalfOf?: string;\n /** For an agent: the client it came through (an MCP client, your workflow), for the audit trail. */\n clientId?: string;\n /** For an agent: the grant or token the person gave it, for the audit trail. */\n grantId?: string;\n};\n\nexport type GuardContext = {\n actor?: ServerActor;\n /** Your roles. Default: `STANDARD_ROLES`. */\n roles?: Role[];\n /** The company the request is for. An actor limited to other entities is refused. */\n entity?: string;\n /** The engagement, case or project: the actor's roles there (`scopes`) count too. */\n scope?: string;\n /** Why, in the actor's words. Kept with the decision. */\n reason?: string;\n /** Refuse unless `reason` has at least this many characters (withdrawing a sign-off, say). */\n minReason?: number;\n /** Your own permissions that only a person may use, added to `PERSON_ONLY`. */\n personOnly?: Permission[];\n /**\n * The person an agent acts for (`actor.onBehalfOf`), with their roles as they\n * are now. Give it, and an agent may only do what that person may do: an id\n * it does not know is refused, and so is a permission or entity the person\n * lacks. Without it `onBehalfOf` is recorded and counts for the duty rules,\n * but the person's roles are not checked.\n */\n personOf?: (id: string) => Actor | undefined;\n /**\n * Permissions an agent has by the company's own rule rather than the person's\n * (approving invoices under a limit, say): `personOf` is not asked for these.\n */\n agentOwn?: Permission[];\n /** What has already been done to this item, and by whom, for the duty rules. */\n deeds?: Deed[];\n /** Default: `STANDARD_DUTY_RULES`. Pass `[]` to switch them off. */\n dutyRules?: DutyRule[];\n /** Language of the refusal sentence. Default: English. */\n locale?: MessageLanguage;\n};\n\nexport type Refusal = {\n ok: false;\n status: 401 | 403 | 409 | 422;\n /** Stable, for your client and your logs. */\n code: string;\n /** One sentence a person or an agent can act on. */\n message: string;\n /** Every problem, where the rule found several. */\n issues?: string[];\n};\n\nexport type Verdict<T> = { ok: true; value: T; actor: string } | Refusal;\n\n/** What `advise` answers: allowed, with what the books say against it, if anything. */\nexport type Advice<T> = { ok: true; value: T | undefined; actor: string; warnings: string[] } | Refusal;\n\n/**\n * Decisions that stay with people, whatever an agent's role says: approving,\n * signing off, finalizing, releasing, closing and submitting.\n */\nexport const PERSON_ONLY: readonly Permission[] = [\n \"audit.review\",\n \"audit.conclude\",\n \"audit.eqcr\",\n \"audit.freeze\",\n \"approval.decide\",\n \"supplier-invoice.approve\",\n \"expense.approve\",\n \"payment.approve\",\n \"payment.release\",\n \"reconciliation.approve\",\n \"period.close\",\n \"period.adjust-closed\",\n \"close.sign-off\",\n \"invoice.finalize\",\n \"vat.submit\",\n \"asset.dispose\",\n \"audit.sign-off\",\n \"finding.confirm\",\n \"finding.withdraw\",\n \"request.send\",\n \"request.decide\",\n \"deal.close\",\n];\n\n/** How an actor appears in the audit trail: `agent:bookkeeper` or the person's id. */\nexport const actorLabel = (actor: ServerActor) => (actor.kind === \"agent\" ? `agent:${actor.id}` : actor.id);\n\n/**\n * The deed to record for what an actor just did, for later duty checks: it\n * names the agent's label and whose session it ran in, so the person cannot\n * review what their own agent prepared.\n */\nexport function actorDeed(actor: ServerActor, permission: Permission): Deed {\n return { actorId: actorLabel(actor), permission, ...(actor.onBehalfOf ? { onBehalfOf: actor.onBehalfOf } : {}) };\n}\n\n/** Everything the audit trail should keep about who acted: the label, the kind, and for an agent whose session, client and grant. */\nexport function actorRecord(actor: ServerActor): {\n actor: string;\n kind: ServerActor[\"kind\"];\n onBehalfOf?: string;\n clientId?: string;\n grantId?: string;\n} {\n return {\n actor: actorLabel(actor),\n kind: actor.kind,\n ...(actor.onBehalfOf ? { onBehalfOf: actor.onBehalfOf } : {}),\n ...(actor.clientId ? { clientId: actor.clientId } : {}),\n ...(actor.grantId ? { grantId: actor.grantId } : {}),\n };\n}\n\nfunction statusOf(code: string): Refusal[\"status\"] {\n if (code === \"permissions.signed-out\") return 401;\n if (code === \"server.reason-required\") return 422;\n if (code.startsWith(\"permissions.\") || code.startsWith(\"server.\")) return 403;\n if (\n /^(period\\.|approval\\.(waiting|rejected)|batch\\.already|invoice\\.(not-editable|number-used)|close\\.)/.test(code)\n ) {\n return 409;\n }\n return 422;\n}\n\nfunction refuse(error: unknown, locale: MessageLanguage | undefined): Refusal {\n if (isBookiError(error)) {\n const issues = Array.isArray(error.params.issues) ? (error.params.issues as unknown[]).map(String) : undefined;\n return {\n ok: false,\n status: statusOf(error.code),\n code: error.code,\n message: locale && locale !== \"en\" ? msgIn(locale, error.code, error.params) : error.message,\n ...(issues\n ? { issues: locale && locale !== \"en\" ? issues.map((issue) => localize(issue, locale)) : issues }\n : {}),\n };\n }\n if (error instanceof DutyRefusal) {\n return {\n ok: false,\n status: 403,\n code: \"permissions.duty\",\n message: locale && locale !== \"en\" ? localize(error.message, locale) : error.message,\n };\n }\n // Your own rule's refusal: its sentence goes back as it is.\n if (error instanceof RuleRefusal) return { ok: false, status: 422, code: \"server.rule\", message: error.message };\n // Anything else (a database error, a bug) is not a refusal, and its message\n // can hold hosts and user names: rethrow it for your error handling.\n throw error;\n}\n\n/**\n * Throw it from a rule of your own to refuse with a sentence of yours: the\n * guard answers 422 `server.rule` with it. Any other error a rule throws is\n * rethrown, so a database error never reaches the caller as a message.\n */\nexport class RuleRefusal extends Error {\n override name = \"RuleRefusal\";\n}\n\n/**\n * The general guard: may this actor do `permission`, and does `rule` pass?\n * The specific guards below are this with the right rule filled in; use it\n * directly for your own actions.\n */\nexport function guard<T>(context: GuardContext, permission: Permission, rule: () => T): Verdict<T> {\n try {\n admit(context, permission);\n return { ok: true, value: rule(), actor: actorLabel(context.actor!) };\n } catch (error) {\n return refuse(error, context.locale);\n }\n}\n\n/**\n * Like `guard`, for actions where the books are a matter of judgment: who may\n * act is still enforced (signed in, a person's decision, role, duties, reason),\n * but what `rule` finds against it comes back as `warnings` instead of a\n * refusal, and `value` is undefined when the rule threw. The person decides.\n */\nexport function advise<T>(context: GuardContext, permission: Permission, rule: () => T): Advice<T> {\n try {\n admit(context, permission);\n } catch (error) {\n return refuse(error, context.locale);\n }\n const actor = actorLabel(context.actor!);\n try {\n return { ok: true, value: rule(), actor, warnings: [] };\n } catch (error) {\n const found = refuse(error, context.locale);\n // Only the books' own objections become warnings; anything about who may act still refuses.\n if (found.status === 409 || found.status === 422) {\n return { ok: true, value: undefined, actor, warnings: found.issues?.length ? found.issues : [found.message] };\n }\n return found;\n }\n}\n\n/** Steps 1 to 5: who may act, and why. Throws a BookiError when not. */\nfunction admit(context: GuardContext, permission: Permission): void {\n const {\n actor,\n roles = STANDARD_ROLES,\n entity,\n scope,\n deeds,\n dutyRules = STANDARD_DUTY_RULES,\n reason,\n minReason,\n } = context;\n // Fail closed: an actor whose kind is neither a person nor an agent is refused outright.\n if (actor && actor.kind !== \"person\" && actor.kind !== \"agent\") {\n throw new BookiError(\"server.unknown-kind\", { kind: String((actor as { kind?: unknown }).kind) });\n }\n const personOnly = PERSON_ONLY.includes(permission) || (context.personOnly ?? []).includes(permission);\n if (actor?.kind === \"agent\" && personOnly) {\n const able = roles.filter((role) => role.permissions.includes(permission)).map((role) => role.name);\n throw new BookiError(\"server.person-only\", {\n permission: String(permission),\n roles: able.join(\", \") || msg(\"permissions.none-defined\"),\n });\n }\n assertCan(actor, roles, permission, { entity, scope, deeds, dutyRules });\n // An agent never does more than the person it acts for could have done.\n if (actor?.kind === \"agent\" && actor.onBehalfOf !== undefined && context.personOf) {\n if (!(context.agentOwn ?? []).includes(permission)) {\n const person = context.personOf(actor.onBehalfOf);\n if (!person || person.id !== actor.onBehalfOf) {\n throw new BookiError(\"server.delegation-unknown\", {\n agent: String(actor.id),\n person: String(actor.onBehalfOf),\n });\n }\n if (entity && person.entities && !person.entities.includes(entity)) {\n throw new BookiError(\"server.delegation-entity\", {\n agent: String(actor.id),\n person: String(person.id),\n entity: String(entity),\n });\n }\n if (!can(person, roles, permission, { scope })) {\n // The roles a person could hold: an agent's own roles are not an answer for them.\n const all = roles.filter((role) => role.permissions.includes(permission));\n const forPeople = all.filter((role) => !actor.roles.includes(role.id));\n const able = (forPeople.length ? forPeople : all).map((role) => role.name);\n throw new BookiError(\"server.delegation\", {\n agent: String(actor.id),\n person: String(person.id),\n permission: String(permission),\n roles: able.join(\", \") || msg(\"permissions.none-defined\"),\n });\n }\n }\n }\n if (minReason && String(reason ?? \"\").trim().length < minReason) {\n throw new BookiError(\"server.reason-required\", { min: minReason });\n }\n}\n\n/**\n * Post a voucher: balanced, closed lists, open period. Only a person with\n * `period.adjust-closed` may post into a soft-closed period; an agent never.\n */\nexport function guardPostVoucher(\n context: GuardContext,\n input: { lines: VoucherLine[]; date: string; rules?: VoucherRules },\n): Verdict<VoucherBalance> {\n const roles = context.roles ?? STANDARD_ROLES;\n const mayAdjustClosed =\n context.actor?.kind === \"person\" && can(context.actor, roles, \"period.adjust-closed\", { entity: context.entity });\n return guard(context, \"voucher.post\", () => {\n // A date that does not exist (\"2026-02-30\") would roll into the next month and past a closed period.\n if (!isIsoDate(input.date))\n throw new BookiError(\"period.posting-date-format\", { value: JSON.stringify(input.date) });\n return assertPostable(input.lines, input.rules ?? {}, { date: input.date, mayAdjustClosed });\n });\n}\n\n/** Record an approval decision. A person's, at the level the chain is waiting for. */\nexport function guardDecideApproval(\n context: GuardContext,\n input: {\n chain: ApprovalLevel[];\n request: ApprovalRequest;\n decision: ApprovalDecision[\"decision\"];\n at: string;\n note?: string;\n },\n): Verdict<ApprovalRequest> {\n return guard(context, \"approval.decide\", () =>\n decide(input.chain, input.request, {\n approverId: context.actor!.id,\n decision: input.decision,\n at: input.at,\n ...(input.note ? { note: input.note } : {}),\n }),\n );\n}\n\n/** Act on something that needs approval first (pay it, post it): only once the chain is through. */\nexport function guardApproved(\n context: GuardContext,\n permission: Permission,\n input: { chain: ApprovalLevel[]; request: ApprovalRequest },\n): Verdict<ApprovalRequest> {\n return guard(context, permission, () => {\n assertApproved(input.chain, input.request);\n return input.request;\n });\n}\n\n/**\n * Release a payment batch to the bank: enough current approvals, no\n * duplicates, and the person releasing did not approve it themselves.\n */\nexport function guardReleasePayments(\n context: GuardContext,\n input: { batch: PaymentBatch; requiredApprovals?: number },\n): Verdict<PaymentBatch> {\n const deeds: Deed[] = [\n ...(context.deeds ?? []),\n ...input.batch.approvals.map((approval) => ({\n actorId: approval.approverId,\n permission: \"payment.approve\" as Permission,\n })),\n ];\n return guard({ ...context, deeds }, \"payment.release\", () => releaseBatch(input.batch, input.requiredApprovals));\n}\n\n/** Close a period: every task done and every sign-off in. */\nexport function guardClosePeriod(context: GuardContext, input: { tasks: CloseTask[] }): Verdict<CloseSummary> {\n return guard(context, \"period.close\", () => assertReadyToClose(input.tasks));\n}\n\n/** Mark a deal won or lost: a person's, recorded under their id. Lost needs a reason. */\nexport function guardCloseDeal(\n context: GuardContext,\n input: { deal: Deal; stages: PipelineStage[]; outcome: DealOutcome; at: string; reason?: string },\n): Verdict<Deal> {\n return guard(context, \"deal.close\", () =>\n closeDeal(input.deal, input.stages, input.outcome, context.actor!.id, input.at, input.reason),\n );\n}\n\n/** Confirm an audit finding: a person's, recorded under their id. Warnings (`findingIssues`) do not refuse it. */\nexport function guardConfirmFinding(context: GuardContext, input: { finding: Finding; at: string }): Verdict<Finding> {\n return guard(context, \"finding.confirm\", () => confirmFinding(input.finding, context.actor!.id, input.at));\n}\n\nconst SIGNOFF_PERMISSION = {\n performed: \"audit.prepare\",\n reviewed: \"audit.review\",\n approved: \"audit.sign-off\",\n} as const satisfies Record<SignoffLevel, Permission>;\n\n/**\n * Sign a level of a document: a person's, recorded under their id. `blockOpenPoints` refuses it while points are open\n * (default: they go with the signature). An agent is refused at every level.\n */\nexport function guardSignDocument(\n context: GuardContext,\n input: { document: SignableDocument; level: SignoffLevel; at: string } & SignoffRules,\n): Verdict<SignableDocument> {\n // An unknown level has no permission of its own: check the sign-off permission, and let signDocument name the level.\n const known = Object.prototype.hasOwnProperty.call(SIGNOFF_PERMISSION, input.level);\n const permission: Permission = known ? SIGNOFF_PERMISSION[input.level] : \"audit.sign-off\";\n const actor = context.actor;\n const name = actor?.name;\n return guard({ ...context, personOnly: [...(context.personOnly ?? []), permission] }, permission, () =>\n signDocument(input.document, input.level, { id: actor!.id, ...(name ? { name } : {}) }, input.at, {\n blockOpenPoints: input.blockOpenPoints,\n }),\n );\n}\n\n/** Finalize a sales invoice under a number: no issues, number unused. */\nexport function guardFinalizeInvoice(\n context: GuardContext,\n input: { invoice: Invoice; number: string; others?: Invoice[] },\n): Verdict<Invoice> {\n return guard(context, \"invoice.finalize\", () => finalizeInvoice(input.invoice, input.number, input.others));\n}\n\n/** Submit a VAT return: computed from a valid schema, with no open issues. */\nexport function guardSubmitVatReturn(\n context: GuardContext,\n input: { computation: VatReturnComputation },\n): Verdict<VatReturnComputation> {\n return guard(context, \"vat.submit\", () => {\n assertVatReturnReady(input.computation);\n return input.computation;\n });\n}\n\n/**\n * A verdict as an HTTP answer, for any framework:\n * `const { status, body } = toHttp(verdict); return Response.json(body, { status })`.\n */\nexport function toHttp<T>(verdict: Verdict<T>): { status: number; body: unknown } {\n if (verdict.ok) return { status: 200, body: { ok: true, actor: verdict.actor, value: verdict.value } };\n const { status, ...body } = verdict;\n return { status, body };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAM,SAAS;AACf,IAAM,UAAU,IAAI,YAAY;AAEhC,IAAM,YAAY,CAAC,UACjB,KAAK,OAAO,aAAa,GAAG,KAAK,CAAC,EAC/B,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,EAAE;AACtB,IA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,EACzB,WAAW;AAAA,EACX,UAAU;AAAA,EACV,UAAU;AACZ;AAMO,SAAS,kBACd,SACA,OAC2B;AAE3B,QAAM,QAAQ,OAAO,UAAU,eAAe,KAAK,oBAAoB,MAAM,KAAK;AAClF,QAAM,aAAyB,QAAQ,mBAAmB,MAAM,KAAK,IAAI;AACzE,QAAM,QAAQ,QAAQ;AACtB,QAAM,OAAO,OAAO;AACpB,SAAO;AAAA,IAAM,EAAE,GAAG,SAAS,YAAY,CAAC,GAAI,QAAQ,cAAc,CAAC,GAAI,UAAU,EAAE;AAAA,IAAG;AAAA,IAAY,MAChG,aAAa,MAAM,UAAU,MAAM,OAAO,EAAE,IAAI,MAAO,IAAI,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG,GAAG,MAAM,IAAI;AAAA,MAChG,iBAAiB,MAAM;AAAA,IACzB,CAAC;AAAA,EACH;AACF;AAGO,SAAS,qBACd,SACA,OACkB;AAClB,SAAO,MAAM,SAAS,oBAAoB,MAAM,gBAAgB,MAAM,SAAS,MAAM,QAAQ,MAAM,MAAM,CAAC;AAC5G;AAGO,SAAS,qBACd,SACA,OAC+B;AAC/B,SAAO,MAAM,SAAS,cAAc,MAAM;AACxC,yBAAqB,MAAM,WAAW;AACtC,WAAO,MAAM;AAAA,EACf,CAAC;AACH;AAMO,SAAS,OAAU,SAAwD;AAChF,MAAI,QAAQ,GAAI,QAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,IAAI,MAAM,OAAO,QAAQ,OAAO,OAAO,QAAQ,MAAM,EAAE;AACrG,QAAM,EAAE,QAAQ,GAAG,KAAK,IAAI;AAC5B,SAAO,EAAE,QAAQ,KAAK;AACxB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/agent-token.ts","../src/server.ts"],"sourcesContent":["/**\n * A short-lived credential of the agent's own, so the server can tell the\n * agent from the person it works for. Your sign-in issues it for a signed-in\n * person; the page sends it with the agent's writes; the server verifies it\n * and adds the agent's roles. Signed with HMAC-SHA-256 through WebCrypto, so\n * it runs in Node, edge runtimes, Deno and Bun.\n *\n * It is not a session: keep the person's own sign-in for their writes.\n */\n\nexport type AgentGrant = {\n /** The agent's id, as `actorLabel` writes it after `agent:`. */\n agentId: string;\n /** The person whose session the agent works in. */\n onBehalfOf: string;\n /** The client it came through (your page, an MCP client). */\n clientId?: string;\n /**\n * What the token is for: an engagement, a company, one API. `verifyAgentToken`\n * with `{ audience }` refuses a token issued for anything else.\n */\n audience?: string;\n /** Seconds it is valid. Default 900 (15 minutes), at most 86 400. */\n ttlSeconds?: number;\n};\n\n/** What a valid token says: add `roles` from your own records to make a `ServerActor`. */\nexport type AgentClaims = {\n id: string;\n kind: \"agent\";\n onBehalfOf: string;\n clientId?: string;\n audience?: string;\n /** This token's own id, for the audit trail (`actorRecord`). */\n grantId: string;\n /** When it stops being valid, in milliseconds since 1970. */\n expiresAt: number;\n};\n\nimport { BookiError } from \"./msg.js\";\n\nconst PREFIX = \"bk1\";\nconst encoder = new TextEncoder();\n\nconst base64url = (bytes: Uint8Array) =>\n btoa(String.fromCharCode(...bytes))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\nconst fromBase64url = (text: string) => {\n const plain = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(plain, (char) => char.charCodeAt(0));\n};\n\nasync function keyFor(secret: string): Promise<CryptoKey> {\n if (typeof secret !== \"string\" || secret.length < 32) {\n throw new BookiError(\"agent-token.secret-short\");\n }\n return crypto.subtle.importKey(\"raw\", encoder.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\n \"sign\",\n \"verify\",\n ]);\n}\n\n/** Issues a token for an agent working for `onBehalfOf`. Call it only for a person your sign-in established. */\nexport async function issueAgentToken(grant: AgentGrant, secret: string, now = Date.now()): Promise<string> {\n const ttl = grant.ttlSeconds ?? 900;\n if (!Number.isSafeInteger(ttl) || ttl < 1 || ttl > 86_400) {\n throw new BookiError(\"agent-token.ttl\", { value: String(ttl) });\n }\n if (!grant.agentId || !grant.onBehalfOf) throw new BookiError(\"agent-token.grant\");\n const claims: AgentClaims = {\n id: grant.agentId,\n kind: \"agent\",\n onBehalfOf: grant.onBehalfOf,\n ...(grant.clientId ? { clientId: grant.clientId } : {}),\n ...(grant.audience ? { audience: grant.audience } : {}),\n grantId: base64url(crypto.getRandomValues(new Uint8Array(12))),\n expiresAt: now + ttl * 1000,\n };\n const payload = base64url(encoder.encode(JSON.stringify(claims)));\n const signature = await crypto.subtle.sign(\"HMAC\", await keyFor(secret), encoder.encode(`${PREFIX}.${payload}`));\n return `${PREFIX}.${payload}.${base64url(new Uint8Array(signature))}`;\n}\n\n/**\n * The claims of a valid, unexpired token signed with `secret`, or null. Null\n * for every failure alike: a caller learns nothing about why.\n */\nexport async function verifyAgentToken(\n token: unknown,\n secret: string,\n now: number | { now?: number; audience?: string } = Date.now(),\n): Promise<AgentClaims | null> {\n const at = typeof now === \"number\" ? now : (now.now ?? Date.now());\n const audience = typeof now === \"number\" ? undefined : now.audience;\n const key = await keyFor(secret);\n if (typeof token !== \"string\" || token.length > 4096) return null;\n const [prefix, payload, signature, ...rest] = token.split(\".\");\n if (prefix !== PREFIX || !payload || !signature || rest.length) return null;\n try {\n const ok = await crypto.subtle.verify(\n \"HMAC\",\n key,\n fromBase64url(signature),\n encoder.encode(`${PREFIX}.${payload}`),\n );\n if (!ok) return null;\n const claims = JSON.parse(new TextDecoder().decode(fromBase64url(payload))) as AgentClaims;\n if (claims.kind !== \"agent\" || typeof claims.id !== \"string\" || typeof claims.onBehalfOf !== \"string\") return null;\n if (!Number.isFinite(claims.expiresAt) || claims.expiresAt <= at) return null;\n // Given an audience, only a token issued for exactly that one passes.\n if (audience !== undefined && claims.audience !== audience) return null;\n return claims;\n } catch {\n return null;\n }\n}\n","/**\n * The same rules the screen enforces, for your API.\n *\n * The controls refuse what a role may not do and what the books do not allow,\n * but a browser is not a security boundary: anything can call your API. Run\n * every write through one of these guards on the server, with the actor your\n * own sign-in established (never one the request says it is). Each guard\n * answers with a verdict you can send straight back: the HTTP status, a stable\n * code and the same sentence the control showed, in English or Norwegian.\n *\n * Order of checks, for every action:\n * 1. Signed in? 401\n * 2. A person's decision, and the actor an agent? 403\n * 3. Role allows it, in this entity? 403\n * And, for an agent acting for someone, theirs? 403 (with `personOf`)\n * 4. Separation of duties against what they did? 403\n * 5. A reason given, where one is required? 422\n * 6. The books allow it (balance, period, approvals, readiness)? 409 or 422\n *\n * Where the books are a matter of professional judgment (an audit file, say),\n * use `advise` instead of `guard`: steps 1 to 5 still refuse, and step 6 comes\n * back as warnings for the person to weigh.\n *\n * Framework-free: plain data in, plain data out. Works in Node, edge runtimes,\n * Deno and Bun.\n */\nexport { type AgentClaims, type AgentGrant, issueAgentToken, verifyAgentToken } from \"./agent-token.js\";\nimport { assertApproved, decide, type ApprovalDecision, type ApprovalLevel, type ApprovalRequest } from \"./approval.js\";\nimport { assertReadyToClose, type CloseSummary, type CloseTask } from \"./close.js\";\nimport { signDocument, type SignableDocument, type SignoffLevel, type SignoffRules } from \"./document-signoff.js\";\nimport { confirmFinding, type Finding } from \"./findings.js\";\nimport { finalizeInvoice, type Invoice } from \"./invoice.js\";\nimport { isIsoDate } from \"./iso-date.js\";\nimport { localize, msgIn, type MessageLanguage } from \"./messages.js\";\nimport { BookiError, isBookiError, msg } from \"./msg.js\";\nimport { releaseBatch, type PaymentBatch } from \"./payment-batch.js\";\nimport { closeDeal, type Deal, type DealOutcome, type PipelineStage } from \"./pipeline.js\";\nimport {\n STANDARD_DUTY_RULES,\n STANDARD_ROLES,\n DutyRefusal,\n assertCan,\n can,\n type Actor,\n type Deed,\n type DutyRule,\n type Permission,\n type Role,\n} from \"./permissions.js\";\nimport { assertVatReturnReady, type VatReturnComputation } from \"./vat-return.js\";\nimport { assertPostable, type VoucherBalance, type VoucherLine, type VoucherRules } from \"./voucher.js\";\n\n/**\n * Who is calling, as your sign-in established it. An agent gets its own\n * credential and comes here as `kind: \"agent\"`; `onBehalfOf` is the person\n * whose session started it. It is recorded, the duty rules count it, and with\n * `personOf` in the context the person's own roles limit what the agent may do.\n */\nexport type ServerActor = Actor & {\n kind: \"person\" | \"agent\";\n onBehalfOf?: string;\n /** For an agent: the client it came through (an MCP client, your workflow), for the audit trail. */\n clientId?: string;\n /** For an agent: the grant or token the person gave it, for the audit trail. */\n grantId?: string;\n};\n\nexport type GuardContext = {\n actor?: ServerActor;\n /** Your roles. Default: `STANDARD_ROLES`. */\n roles?: Role[];\n /** The company the request is for. An actor limited to other entities is refused. */\n entity?: string;\n /** The engagement, case or project: the actor's roles there (`scopes`) count too. */\n scope?: string;\n /** Why, in the actor's words. Kept with the decision. */\n reason?: string;\n /** Refuse unless `reason` has at least this many characters (withdrawing a sign-off, say). */\n minReason?: number;\n /** Your own permissions that only a person may use, added to `PERSON_ONLY`. */\n personOnly?: Permission[];\n /**\n * The person an agent acts for (`actor.onBehalfOf`), with their roles as they\n * are now. Give it, and an agent may only do what that person may do: an id\n * it does not know is refused, and so is a permission or entity the person\n * lacks. Without it `onBehalfOf` is recorded and counts for the duty rules,\n * but the person's roles are not checked.\n */\n personOf?: (id: string) => Actor | undefined;\n /**\n * Permissions an agent has by the company's own rule rather than the person's\n * (approving invoices under a limit, say): `personOf` is not asked for these.\n */\n agentOwn?: Permission[];\n /** What has already been done to this item, and by whom, for the duty rules. */\n deeds?: Deed[];\n /** Default: `STANDARD_DUTY_RULES`. Pass `[]` to switch them off. */\n dutyRules?: DutyRule[];\n /** Language of the refusal sentence. Default: English. */\n locale?: MessageLanguage;\n};\n\nexport type Refusal = {\n ok: false;\n status: 401 | 403 | 409 | 422;\n /** Stable, for your client and your logs. */\n code: string;\n /** One sentence a person or an agent can act on. */\n message: string;\n /** Every problem, where the rule found several. */\n issues?: string[];\n};\n\nexport type Verdict<T> = { ok: true; value: T; actor: string } | Refusal;\n\n/** What `advise` answers: allowed, with what the books say against it, if anything. */\nexport type Advice<T> = { ok: true; value: T | undefined; actor: string; warnings: string[] } | Refusal;\n\n/**\n * Decisions that stay with people, whatever an agent's role says: approving,\n * signing off, finalizing, releasing, closing and submitting.\n */\nexport const PERSON_ONLY: readonly Permission[] = [\n \"audit.review\",\n \"audit.conclude\",\n \"audit.eqcr\",\n \"audit.freeze\",\n \"approval.decide\",\n \"supplier-invoice.approve\",\n \"expense.approve\",\n \"payment.approve\",\n \"payment.release\",\n \"reconciliation.approve\",\n \"period.close\",\n \"period.adjust-closed\",\n \"close.sign-off\",\n \"invoice.finalize\",\n \"vat.submit\",\n \"asset.dispose\",\n \"audit.sign-off\",\n \"finding.confirm\",\n \"finding.withdraw\",\n \"request.send\",\n \"request.decide\",\n \"deal.close\",\n];\n\n/** How an actor appears in the audit trail: `agent:bookkeeper` or the person's id. */\nexport const actorLabel = (actor: ServerActor) => (actor.kind === \"agent\" ? `agent:${actor.id}` : actor.id);\n\n/**\n * The deed to record for what an actor just did, for later duty checks: it\n * names the agent's label and whose session it ran in, so the person cannot\n * review what their own agent prepared.\n */\nexport function actorDeed(actor: ServerActor, permission: Permission): Deed {\n return { actorId: actorLabel(actor), permission, ...(actor.onBehalfOf ? { onBehalfOf: actor.onBehalfOf } : {}) };\n}\n\n/** Everything the audit trail should keep about who acted: the label, the kind, and for an agent whose session, client and grant. */\nexport function actorRecord(actor: ServerActor): {\n actor: string;\n kind: ServerActor[\"kind\"];\n onBehalfOf?: string;\n clientId?: string;\n grantId?: string;\n} {\n return {\n actor: actorLabel(actor),\n kind: actor.kind,\n ...(actor.onBehalfOf ? { onBehalfOf: actor.onBehalfOf } : {}),\n ...(actor.clientId ? { clientId: actor.clientId } : {}),\n ...(actor.grantId ? { grantId: actor.grantId } : {}),\n };\n}\n\nfunction statusOf(code: string): Refusal[\"status\"] {\n if (code === \"permissions.signed-out\") return 401;\n if (code === \"server.reason-required\") return 422;\n if (code.startsWith(\"permissions.\") || code.startsWith(\"server.\")) return 403;\n if (\n /^(period\\.|approval\\.(waiting|rejected)|batch\\.already|invoice\\.(not-editable|number-used)|close\\.)/.test(code)\n ) {\n return 409;\n }\n return 422;\n}\n\nfunction refuse(error: unknown, locale: MessageLanguage | undefined): Refusal {\n if (isBookiError(error)) {\n const issues = Array.isArray(error.params.issues) ? (error.params.issues as unknown[]).map(String) : undefined;\n return {\n ok: false,\n status: statusOf(error.code),\n code: error.code,\n message: locale && locale !== \"en\" ? msgIn(locale, error.code, error.params) : error.message,\n ...(issues\n ? { issues: locale && locale !== \"en\" ? issues.map((issue) => localize(issue, locale)) : issues }\n : {}),\n };\n }\n if (error instanceof DutyRefusal) {\n return {\n ok: false,\n status: 403,\n code: \"permissions.duty\",\n message: locale && locale !== \"en\" ? localize(error.message, locale) : error.message,\n };\n }\n // Your own rule's refusal: its sentence goes back as it is.\n if (error instanceof RuleRefusal) return { ok: false, status: 422, code: \"server.rule\", message: error.message };\n // Anything else (a database error, a bug) is not a refusal, and its message\n // can hold hosts and user names: rethrow it for your error handling.\n throw error;\n}\n\n/**\n * Throw it from a rule of your own to refuse with a sentence of yours: the\n * guard answers 422 `server.rule` with it. Any other error a rule throws is\n * rethrown, so a database error never reaches the caller as a message.\n */\nexport class RuleRefusal extends Error {\n override name = \"RuleRefusal\";\n}\n\n/**\n * The general guard: may this actor do `permission`, and does `rule` pass?\n * The specific guards below are this with the right rule filled in; use it\n * directly for your own actions.\n */\nexport function guard<T>(context: GuardContext, permission: Permission, rule: () => T): Verdict<T> {\n try {\n admit(context, permission);\n return { ok: true, value: rule(), actor: actorLabel(context.actor!) };\n } catch (error) {\n return refuse(error, context.locale);\n }\n}\n\n/**\n * Like `guard`, for actions where the books are a matter of judgment: who may\n * act is still enforced (signed in, a person's decision, role, duties, reason),\n * but what `rule` finds against it comes back as `warnings` instead of a\n * refusal, and `value` is undefined when the rule threw. The person decides.\n */\nexport function advise<T>(context: GuardContext, permission: Permission, rule: () => T): Advice<T> {\n try {\n admit(context, permission);\n } catch (error) {\n return refuse(error, context.locale);\n }\n const actor = actorLabel(context.actor!);\n try {\n return { ok: true, value: rule(), actor, warnings: [] };\n } catch (error) {\n const found = refuse(error, context.locale);\n // Only the books' own objections become warnings; anything about who may act still refuses.\n if (found.status === 409 || found.status === 422) {\n return { ok: true, value: undefined, actor, warnings: found.issues?.length ? found.issues : [found.message] };\n }\n return found;\n }\n}\n\n/** Steps 1 to 5: who may act, and why. Throws a BookiError when not. */\nfunction admit(context: GuardContext, permission: Permission): void {\n const {\n actor,\n roles = STANDARD_ROLES,\n entity,\n scope,\n deeds,\n dutyRules = STANDARD_DUTY_RULES,\n reason,\n minReason,\n } = context;\n // Fail closed: an actor whose kind is neither a person nor an agent is refused outright.\n if (actor && actor.kind !== \"person\" && actor.kind !== \"agent\") {\n throw new BookiError(\"server.unknown-kind\", { kind: String((actor as { kind?: unknown }).kind) });\n }\n const personOnly = PERSON_ONLY.includes(permission) || (context.personOnly ?? []).includes(permission);\n if (actor?.kind === \"agent\" && personOnly) {\n // Who to ask: a role the refused agent holds is no answer for the reader.\n const able = roles\n .filter((role) => role.permissions.includes(permission) && !actor.roles.includes(role.id))\n .map((role) => role.name);\n throw new BookiError(\"server.person-only\", {\n permission: String(permission),\n roles: able.join(\", \") || msg(\"permissions.none-defined\"),\n });\n }\n assertCan(actor, roles, permission, { entity, scope, deeds, dutyRules });\n // An agent never does more than the person it acts for could have done.\n if (actor?.kind === \"agent\" && actor.onBehalfOf !== undefined && context.personOf) {\n if (!(context.agentOwn ?? []).includes(permission)) {\n const person = context.personOf(actor.onBehalfOf);\n if (!person || person.id !== actor.onBehalfOf) {\n throw new BookiError(\"server.delegation-unknown\", {\n agent: String(actor.id),\n person: String(actor.onBehalfOf),\n });\n }\n if (entity && person.entities && !person.entities.includes(entity)) {\n throw new BookiError(\"server.delegation-entity\", {\n agent: String(actor.id),\n person: String(person.id),\n entity: String(entity),\n });\n }\n if (!can(person, roles, permission, { scope })) {\n // The roles a person could hold: an agent's own roles are not an answer for them.\n const all = roles.filter((role) => role.permissions.includes(permission));\n const forPeople = all.filter((role) => !actor.roles.includes(role.id));\n const able = (forPeople.length ? forPeople : all).map((role) => role.name);\n throw new BookiError(\"server.delegation\", {\n agent: String(actor.id),\n person: String(person.id),\n permission: String(permission),\n roles: able.join(\", \") || msg(\"permissions.none-defined\"),\n });\n }\n }\n }\n if (minReason && String(reason ?? \"\").trim().length < minReason) {\n throw new BookiError(\"server.reason-required\", { min: minReason });\n }\n}\n\n/**\n * Post a voucher: balanced, closed lists, open period. Only a person with\n * `period.adjust-closed` may post into a soft-closed period; an agent never.\n */\nexport function guardPostVoucher(\n context: GuardContext,\n input: { lines: VoucherLine[]; date: string; rules?: VoucherRules },\n): Verdict<VoucherBalance> {\n const roles = context.roles ?? STANDARD_ROLES;\n const mayAdjustClosed =\n context.actor?.kind === \"person\" && can(context.actor, roles, \"period.adjust-closed\", { entity: context.entity });\n return guard(context, \"voucher.post\", () => {\n // A date that does not exist (\"2026-02-30\") would roll into the next month and past a closed period.\n if (!isIsoDate(input.date))\n throw new BookiError(\"period.posting-date-format\", { value: JSON.stringify(input.date) });\n return assertPostable(input.lines, input.rules ?? {}, { date: input.date, mayAdjustClosed });\n });\n}\n\n/** Record an approval decision. A person's, at the level the chain is waiting for. */\nexport function guardDecideApproval(\n context: GuardContext,\n input: {\n chain: ApprovalLevel[];\n request: ApprovalRequest;\n decision: ApprovalDecision[\"decision\"];\n at: string;\n note?: string;\n },\n): Verdict<ApprovalRequest> {\n return guard(context, \"approval.decide\", () =>\n decide(input.chain, input.request, {\n approverId: context.actor!.id,\n decision: input.decision,\n at: input.at,\n ...(input.note ? { note: input.note } : {}),\n }),\n );\n}\n\n/** Act on something that needs approval first (pay it, post it): only once the chain is through. */\nexport function guardApproved(\n context: GuardContext,\n permission: Permission,\n input: { chain: ApprovalLevel[]; request: ApprovalRequest },\n): Verdict<ApprovalRequest> {\n return guard(context, permission, () => {\n assertApproved(input.chain, input.request);\n return input.request;\n });\n}\n\n/**\n * Release a payment batch to the bank: enough current approvals, no\n * duplicates, and the person releasing did not approve it themselves.\n */\nexport function guardReleasePayments(\n context: GuardContext,\n input: { batch: PaymentBatch; requiredApprovals?: number },\n): Verdict<PaymentBatch> {\n const deeds: Deed[] = [\n ...(context.deeds ?? []),\n ...input.batch.approvals.map((approval) => ({\n actorId: approval.approverId,\n permission: \"payment.approve\" as Permission,\n })),\n ];\n return guard({ ...context, deeds }, \"payment.release\", () => releaseBatch(input.batch, input.requiredApprovals));\n}\n\n/** Close a period: every task done and every sign-off in. */\nexport function guardClosePeriod(context: GuardContext, input: { tasks: CloseTask[] }): Verdict<CloseSummary> {\n return guard(context, \"period.close\", () => assertReadyToClose(input.tasks));\n}\n\n/** Mark a deal won or lost: a person's, recorded under their id. Lost needs a reason. */\nexport function guardCloseDeal(\n context: GuardContext,\n input: { deal: Deal; stages: PipelineStage[]; outcome: DealOutcome; at: string; reason?: string },\n): Verdict<Deal> {\n return guard(context, \"deal.close\", () =>\n closeDeal(input.deal, input.stages, input.outcome, context.actor!.id, input.at, input.reason),\n );\n}\n\n/** Confirm an audit finding: a person's, recorded under their id. Warnings (`findingIssues`) do not refuse it. */\nexport function guardConfirmFinding(context: GuardContext, input: { finding: Finding; at: string }): Verdict<Finding> {\n return guard(context, \"finding.confirm\", () => confirmFinding(input.finding, context.actor!.id, input.at));\n}\n\nconst SIGNOFF_PERMISSION = {\n performed: \"audit.prepare\",\n reviewed: \"audit.review\",\n approved: \"audit.sign-off\",\n} as const satisfies Record<SignoffLevel, Permission>;\n\n/**\n * Sign a level of a document: a person's, recorded under their id. `blockOpenPoints` refuses it while points are open\n * (default: they go with the signature). An agent is refused at every level.\n */\nexport function guardSignDocument(\n context: GuardContext,\n input: { document: SignableDocument; level: SignoffLevel; at: string } & SignoffRules,\n): Verdict<SignableDocument> {\n // An unknown level has no permission of its own: check the sign-off permission, and let signDocument name the level.\n const known = Object.prototype.hasOwnProperty.call(SIGNOFF_PERMISSION, input.level);\n const permission: Permission = known ? SIGNOFF_PERMISSION[input.level] : \"audit.sign-off\";\n const actor = context.actor;\n const name = actor?.name;\n return guard({ ...context, personOnly: [...(context.personOnly ?? []), permission] }, permission, () =>\n signDocument(input.document, input.level, { id: actor!.id, ...(name ? { name } : {}) }, input.at, {\n blockOpenPoints: input.blockOpenPoints,\n }),\n );\n}\n\n/** Finalize a sales invoice under a number: no issues, number unused. */\nexport function guardFinalizeInvoice(\n context: GuardContext,\n input: { invoice: Invoice; number: string; others?: Invoice[] },\n): Verdict<Invoice> {\n return guard(context, \"invoice.finalize\", () => finalizeInvoice(input.invoice, input.number, input.others));\n}\n\n/** Submit a VAT return: computed from a valid schema, with no open issues. */\nexport function guardSubmitVatReturn(\n context: GuardContext,\n input: { computation: VatReturnComputation },\n): Verdict<VatReturnComputation> {\n return guard(context, \"vat.submit\", () => {\n assertVatReturnReady(input.computation);\n return input.computation;\n });\n}\n\n/**\n * A verdict as an HTTP answer, for any framework:\n * `const { status, body } = toHttp(verdict); return Response.json(body, { status })`.\n */\nexport function toHttp<T>(verdict: Verdict<T>): { status: number; body: HttpBody<T> } {\n if (verdict.ok) return { status: 200, body: { ok: true, actor: verdict.actor, value: verdict.value } };\n const { status, ...body } = verdict;\n return { status, body };\n}\n\n/** What `toHttp` answers with: the value on success, `{ ok: false, code, message, issues? }` on a refusal. */\nexport type HttpBody<T> = { ok: true; actor: string; value: T } | Omit<Refusal, \"status\">;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAM,SAAS;AACf,IAAM,UAAU,IAAI,YAAY;AAEhC,IAAM,YAAY,CAAC,UACjB,KAAK,OAAO,aAAa,GAAG,KAAK,CAAC,EAC/B,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,EAAE;AACtB,IAAM,gBAAgB,CAAC,SAAiB;AACtC,QAAM,QAAQ,KAAK,KAAK,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG,CAAC;AAC7D,SAAO,WAAW,KAA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3B,QAAM,QAAQ,OAAO,UAAU,eAAe,KAAK,oBAAoB,MAAM,KAAK;AAClF,QAAM,aAAyB,QAAQ,mBAAmB,MAAM,KAAK,IAAI;AACzE,QAAM,QAAQ,QAAQ;AACtB,QAAM,OAAO,OAAO;AACpB,SAAO;AAAA,IAAM,EAAE,GAAG,SAAS,YAAY,CAAC,GAAI,QAAQ,cAAc,CAAC,GAAI,UAAU,EAAE;AAAA,IAAG;AAAA,IAAY,MAChG,aAAa,MAAM,UAAU,MAAM,OAAO,EAAE,IAAI,MAAO,IAAI,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG,GAAG,MAAM,IAAI;AAAA,MAChG,iBAAiB,MAAM;AAAA,IACzB,CAAC;AAAA,EACH;AACF;AAGO,SAAS,qBACd,SACA,OACkB;AAClB,SAAO,MAAM,SAAS,oBAAoB,MAAM,gBAAgB,MAAM,SAAS,MAAM,QAAQ,MAAM,MAAM,CAAC;AAC5G;AAGO,SAAS,qBACd,SACA,OAC+B;AAC/B,SAAO,MAAM,SAAS,cAAc,MAAM;AACxC,yBAAqB,MAAM,WAAW;AACtC,WAAO,MAAM;AAAA,EACf,CAAC;AACH;AAMO,SAAS,OAAU,SAA4D;AACpF,MAAI,QAAQ,GAAI,QAAO,EAAE,QAAQ,KAAK,MAAM,EAAE,IAAI,MAAM,OAAO,QAAQ,OAAO,OAAO,QAAQ,MAAM,EAAE;AACrG,QAAM,EAAE,QAAQ,GAAG,KAAK,IAAI;AAC5B,SAAO,EAAE,QAAQ,KAAK;AACxB;","names":[]}
|
package/dist/supplier-invoice.js
CHANGED
|
@@ -13,8 +13,8 @@ import {
|
|
|
13
13
|
redactSupplierInvoice,
|
|
14
14
|
rejectSupplierInvoice,
|
|
15
15
|
supplierInvoiceIssues
|
|
16
|
-
} from "./chunk-
|
|
17
|
-
import "./chunk-
|
|
16
|
+
} from "./chunk-XSBPSQMB.js";
|
|
17
|
+
import "./chunk-J3LLJEU2.js";
|
|
18
18
|
export {
|
|
19
19
|
DEFAULT_CONFIDENCE_THRESHOLD,
|
|
20
20
|
SUPPLIER_INVOICE_FIELDS,
|
package/dist/table.js
CHANGED
package/dist/vat-return.js
CHANGED
|
@@ -9,10 +9,10 @@ import {
|
|
|
9
9
|
vatBoxVouchers,
|
|
10
10
|
vatReturnIssues,
|
|
11
11
|
vatSchemaIssues
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-HCJY7UL5.js";
|
|
13
13
|
import "./chunk-ICBA5A2V.js";
|
|
14
|
-
import "./chunk-
|
|
15
|
-
import "./chunk-
|
|
14
|
+
import "./chunk-PLYGQ63I.js";
|
|
15
|
+
import "./chunk-J3LLJEU2.js";
|
|
16
16
|
export {
|
|
17
17
|
DRAFT_VAT_FILING,
|
|
18
18
|
GENERIC_VAT_SCHEMA_EXAMPLE,
|
package/dist/voucher.js
CHANGED
|
@@ -22,13 +22,13 @@ import {
|
|
|
22
22
|
validateVoucherLine,
|
|
23
23
|
vatPostings,
|
|
24
24
|
voucherIssues
|
|
25
|
-
} from "./chunk-
|
|
26
|
-
import "./chunk-
|
|
25
|
+
} from "./chunk-4F5QLWKQ.js";
|
|
26
|
+
import "./chunk-YGHY2MVR.js";
|
|
27
27
|
import "./chunk-ICBA5A2V.js";
|
|
28
|
-
import "./chunk-
|
|
29
|
-
import "./chunk-
|
|
30
|
-
import "./chunk-
|
|
31
|
-
import "./chunk-
|
|
28
|
+
import "./chunk-PLYGQ63I.js";
|
|
29
|
+
import "./chunk-DT3HAYKU.js";
|
|
30
|
+
import "./chunk-TYL4PAUC.js";
|
|
31
|
+
import "./chunk-J3LLJEU2.js";
|
|
32
32
|
import "./chunk-ZJXNLPER.js";
|
|
33
33
|
export {
|
|
34
34
|
applyAccountRules,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@booki-aui/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Booki core — the accounting rules behind agent-first apps: integer money, locale profiles, validators, ledger and table logic. Framework-agnostic. Norway and US profiles are supported; SE, DK, GB and DE are experimental starters.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|