@lunora/server 1.0.0-alpha.2 → 1.0.0-alpha.200

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 (92) hide show
  1. package/LICENSE.md +219 -0
  2. package/README.md +57 -1
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/data-model.d.mts +490 -142
  5. package/dist/data-model.d.ts +490 -142
  6. package/dist/data-model.mjs +0 -1
  7. package/dist/drizzle.mjs +1 -1
  8. package/dist/in-process.d.mts +101 -0
  9. package/dist/in-process.d.ts +101 -0
  10. package/dist/in-process.mjs +1 -0
  11. package/dist/index.d.mts +3592 -1378
  12. package/dist/index.d.ts +3592 -1378
  13. package/dist/index.mjs +1 -24
  14. package/dist/otel.d.mts +554 -0
  15. package/dist/otel.d.ts +554 -0
  16. package/dist/otel.mjs +1 -0
  17. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BFmhdKJG.mjs +1 -0
  18. package/dist/packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs +1 -0
  19. package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BeS7G0yM.mjs +1 -0
  20. package/dist/packem_shared/LunoraEnvError-bkdMu_-N.mjs +4 -0
  21. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-DFpy5J8G.mjs +1 -0
  22. package/dist/packem_shared/allowAll-DkRAgItV.mjs +1 -0
  23. package/dist/packem_shared/apply-output-C5wZ5EAL.mjs +1 -0
  24. package/dist/packem_shared/asBucketStorage-DoGYOjq3.mjs +1 -0
  25. package/dist/packem_shared/assertShapesDeclareReadPolicies-isd_Yupt.mjs +1 -0
  26. package/dist/packem_shared/beginDeferredDeletes-DhwFBbvs.mjs +1 -0
  27. package/dist/packem_shared/beginDeferredSchedules-n_pHHjPE.mjs +1 -0
  28. package/dist/packem_shared/bindOrm-BHq_oUP2.mjs +1 -0
  29. package/dist/packem_shared/buildMaskRegistry-DpWMtalG.mjs +1 -0
  30. package/dist/packem_shared/compose-middleware-BK9FlblN.mjs +1 -0
  31. package/dist/packem_shared/composePluginMiddleware-ZtDIkbvJ.mjs +1 -0
  32. package/dist/packem_shared/context-identity-B2XYGA0B.mjs +1 -0
  33. package/dist/packem_shared/createPolicyDsl-BZa6SqLJ.mjs +1 -0
  34. package/dist/packem_shared/createSecrets-D6rLB42U.mjs +1 -0
  35. package/dist/packem_shared/createServices-IJvoqi0e.mjs +1 -0
  36. package/dist/packem_shared/defineAggregateIndex-DF8NiKHr.mjs +1 -0
  37. package/dist/packem_shared/defineIdentity-DwkNKwYa.mjs +1 -0
  38. package/dist/packem_shared/defineIdentityGuard-Bt8N65Zs.mjs +1 -0
  39. package/dist/packem_shared/defineMigration-CXOS0Bvq.mjs +1 -0
  40. package/dist/packem_shared/defineModule-OecXWM3U.mjs +1 -0
  41. package/dist/packem_shared/defineMutator-B4ipDtDR.mjs +1 -0
  42. package/dist/packem_shared/defineShape-CX9Xs8AY.mjs +1 -0
  43. package/dist/packem_shared/defineStorageRule-Dv4nJE0H.mjs +1 -0
  44. package/dist/packem_shared/fnv1a-D3ueNTWB.mjs +1 -0
  45. package/dist/packem_shared/functions-B2-H4PQT.mjs +1 -0
  46. package/dist/packem_shared/httpAction-CsKNC6op.mjs +5 -0
  47. package/dist/packem_shared/initLunora-B-7Xs3Qq.mjs +1 -0
  48. package/dist/packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs +1 -0
  49. package/dist/packem_shared/mask-BdULkLAu.mjs +1 -0
  50. package/dist/packem_shared/middleware-DbhB1jRk.mjs +1 -0
  51. package/dist/packem_shared/onConnect-BLRoOpv2.mjs +1 -0
  52. package/dist/packem_shared/onQueryChange-CatdYnH5.mjs +1 -0
  53. package/dist/packem_shared/onWhisper-CfDbFLQh.mjs +1 -0
  54. package/dist/packem_shared/platformAdmin-kczXQme8.mjs +1 -0
  55. package/dist/packem_shared/plugin-Bm9wIpiI.mjs +1 -0
  56. package/dist/packem_shared/policy-tag-V0lqFzgS.mjs +1 -0
  57. package/dist/packem_shared/protectPublic-Bi5_95aP.mjs +1 -0
  58. package/dist/packem_shared/rls-B3xf3YrN.mjs +1 -0
  59. package/dist/packem_shared/run-middleware-BefYq7Xd.mjs +1 -0
  60. package/dist/packem_shared/serveStorageObject-DNN3r8x3.mjs +1 -0
  61. package/dist/packem_shared/stable-key-B_BlboiY.mjs +1 -0
  62. package/dist/packem_shared/storageRules-CMfQu8yY.mjs +1 -0
  63. package/dist/packem_shared/types.d-B7FLdYUD.d.mts +148 -0
  64. package/dist/packem_shared/types.d-BCtjbIzl.d.ts +148 -0
  65. package/dist/packem_shared/wire-codec-CZ4obM6q.mjs +1 -0
  66. package/dist/rls/testing.d.mts +42 -34
  67. package/dist/rls/testing.d.ts +42 -34
  68. package/dist/rls/testing.mjs +1 -49
  69. package/dist/types.d.mts +2301 -512
  70. package/dist/types.d.ts +2301 -512
  71. package/dist/types.mjs +0 -31
  72. package/package.json +24 -6
  73. package/dist/packem_shared/LunoraEnvError-DjFkpkSP.mjs +0 -187
  74. package/dist/packem_shared/LunoraError-DhggBJZF.mjs +0 -51
  75. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-BZYd5-uo.mjs +0 -114
  76. package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
  77. package/dist/packem_shared/bindOrm-DCuyr46L.mjs +0 -71
  78. package/dist/packem_shared/composePluginMiddleware-Ck5_TUO8.mjs +0 -100
  79. package/dist/packem_shared/createPolicyDsl-De67zPDS.mjs +0 -29
  80. package/dist/packem_shared/defineAggregateIndex-DxSso0rH.mjs +0 -236
  81. package/dist/packem_shared/defineMigration-CAJLr6fx.mjs +0 -8
  82. package/dist/packem_shared/defineStorageRule-qu0mpilX.mjs +0 -20
  83. package/dist/packem_shared/httpAction-B7FYUEgr.mjs +0 -340
  84. package/dist/packem_shared/initLunora-CATvPsVt.mjs +0 -86
  85. package/dist/packem_shared/mask-Jc84C_hK.mjs +0 -211
  86. package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
  87. package/dist/packem_shared/protectPublic-BjFkQ_Or.mjs +0 -15
  88. package/dist/packem_shared/rls-BDKRbMCA.mjs +0 -551
  89. package/dist/packem_shared/run-middleware-CYQOuoV6.mjs +0 -18
  90. package/dist/packem_shared/storageRules-4a30FSpI.mjs +0 -88
  91. package/dist/packem_shared/types.d-BDY0FYHK.d.ts +0 -135
  92. package/dist/packem_shared/types.d-DmvyEMD6.d.mts +0 -135
@@ -0,0 +1 @@
1
+ const m=e=>{let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)},A=e=>{const t=atob(e),c=new Uint8Array(t.length);for(let o=0;o<t.length;o+=1)c[o]=t.codePointAt(o)??0;return c},i="$lunora.wire$";const w="__proto__",g={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},p={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},u=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[i,"undefined"];if(e===null)return null;const c=typeof e;if(c==="bigint"){const r=e.toString();if(r.length>1024)throw new RangeError("wire-codec: over-long bigint (max 1024 digits)");return[i,"bigint",r]}if(c==="number"){const r=e;return Number.isNaN(r)?[i,"nan"]:r===1/0?[i,"inf"]:r===-1/0?[i,"-inf"]:r}if(c!=="object")return e;if(e instanceof Date)return[i,"date",u(e.getTime(),t+1)];if(e instanceof Error){const r=e,n=u(Object.fromEntries(Object.keys(r).map(a=>[a,r[a]])),t+1),s=[i,"error",String(r.name),String(r.message),n];return r.cause!==void 0&&s.push(u(r.cause,t+1)),s}if(e instanceof URL)return[i,"url",e.href];if(e instanceof Map)return[i,"map",[...e.entries()].map(([r,n])=>[u(r,t+1),u(n,t+1)])];if(e instanceof Set)return[i,"set",[...e].map(r=>u(r,t+1))];if(e instanceof ArrayBuffer)return[i,"bytes",m(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,n=r.constructor.name,s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return n==="Uint8Array"?[i,"bytes",m(s)]:[i,"bytes",m(s),n]}if(Array.isArray(e)){const r=e.map(n=>u(n,t+1));return r.length>0&&r[0]===i?[i,"arr",r]:r}if(!l(e)){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const o=e,f={};for(const r of Object.keys(o)){const n=o[r];if(n===void 0)continue;const s=u(n,t+1);r===w?Object.defineProperty(f,r,{configurable:!0,enumerable:!0,value:s,writable:!0}):f[r]=s}return f},y=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===i)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(r=>y(r,t+1));case"bigint":{const r=e[2];if(typeof r!="string"||r.length>1024||!/^-?\d+$/.test(r))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(r)}case"date":{const r=y(e[2],t+1);if(typeof r!="number")throw new TypeError("wire-codec: malformed date — epoch must be a number");return new Date(r)}case"map":{const r=e[2];return new Map(r.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(e[2].map(r=>y(r,t+1)));case"url":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed url — href must be a string");return new URL(r)}case"error":{const r=e[2],n=e[3];if(typeof r!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error — name and message must be strings");const s=(Object.hasOwn(p,r)?p[r]:void 0)??Error,a=new s(n);a.name!==r&&Object.defineProperty(a,"name",{configurable:!0,value:r,writable:!0});const b=y(e[4],t+1);if(b===null||typeof b!="object"||Array.isArray(b))throw new TypeError("wire-codec: malformed error — props must be an object");for(const d of Object.keys(b))d===w?Object.defineProperty(a,d,{configurable:!0,enumerable:!0,value:b[d],writable:!0}):a[d]=b[d];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(e[5],t+1),writable:!0}),a}case"bytes":{const r=e[2];if(typeof r!="string")throw new TypeError("wire-codec: malformed bytes — payload must be a base64 string");const n=A(r);if(m(n)!==r)throw new TypeError("wire-codec: malformed bytes — payload must be canonical padded base64");const s=e[3]??"Uint8Array";if(s==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const a=Object.hasOwn(g,s)?g[s]:void 0;return a?new a(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(r=>y(r,t+1))}return e.map(f=>y(f,t+1))}const c=e,o={};for(const f of Object.keys(c)){const r=y(c[f],t+1);f===w?Object.defineProperty(o,f,{configurable:!0,enumerable:!0,value:r,writable:!0}):o[f]=r}return o},E=(e,t,c)=>{try{return u(c)}catch(o){throw new TypeError(`${e}: cannot encode args for '${t}' — ${o instanceof Error?o.message:String(o)}`,o instanceof Error?{cause:o}:void 0)}};export{E as a,y as d,u as e,l as i};
@@ -1,48 +1,56 @@
1
- import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-DmvyEMD6.mjs";
1
+ import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-B7FLdYUD.mjs";
2
2
  import "../data-model.mjs";
3
3
  /**
4
- * The slice of a request identity a policy reads. Mirrors the
5
- * `PolicyContext.auth` shape the middleware builds at request time — every
6
- * field is optional and defaults the same way the middleware defaults it
7
- * (`userId`/`identity` → `null`, `roles` → `[]`).
8
- */
4
+ * The slice of a request identity a policy reads. Mirrors the
5
+ * `PolicyContext.auth` shape the middleware builds at request time — every
6
+ * field is optional and defaults the same way the middleware defaults it
7
+ * (`userId`/`identity` → `null`, `roles` → the `roles` claim on `identity`).
8
+ *
9
+ * There is deliberately NO separate `roles` field: `auth.roles` is derived from
10
+ * the identity claims by the same `readIdentityRoles` the middleware uses, so
11
+ * the harness cannot set up a world the runtime is unable to produce. Give a
12
+ * role-branched policy its roles the way production does —
13
+ * `.as({ identity: { roles: ["admin"] }, userId: "u1" })`.
14
+ */
9
15
  interface TestIdentity {
10
- /** Raw identity claims a policy may branch on (`auth.identity.email`, …). */
16
+ /**
17
+ * Raw identity claims a policy may branch on (`auth.identity.email`, …).
18
+ * The `roles` claim (a `string[]` or a comma-separated string) is what
19
+ * populates `auth.roles` and backs `auth.can(...)`.
20
+ */
11
21
  identity?: Record<string, unknown> | null;
12
- /** Role labels the request carries; resolved to permissions via the harness `roles` registry. */
13
- roles?: ReadonlyArray<string>;
14
22
  /** The caller id (`auth.userId`); `null`/omitted is the anonymous caller. */
15
23
  userId?: null | string;
16
24
  }
17
25
  /** Options for {@link expectPolicy}. */
18
26
  interface ExpectPolicyOptions<Context = unknown> {
19
27
  /**
20
- * The procedure context a policy reads via `ctx` (e.g. `ctx.orgId`). Held
21
- * for the whole harness; pass a fresh `expectPolicy(..., { ctx })` for a
22
- * different context. Defaults to an empty object.
23
- */
28
+ * The procedure context a policy reads via `ctx` (e.g. `ctx.orgId`). Held
29
+ * for the whole harness; pass a fresh `expectPolicy(..., { ctx })` for a
30
+ * different context. Defaults to an empty object.
31
+ */
24
32
  ctx?: Context;
25
33
  /**
26
- * Role→permission grants backing `auth.can(...)` — the same registry passed
27
- * to `rls(policies, { roles })`. A role not listed here grants nothing, so
28
- * `can(...)` fails closed exactly as it does in production.
29
- */
34
+ * Role→permission grants backing `auth.can(...)` — the same registry passed
35
+ * to `rls(policies, { roles })`. A role not listed here grants nothing, so
36
+ * `can(...)` fails closed exactly as it does in production.
37
+ */
30
38
  roles?: ReadonlyArray<Role>;
31
39
  }
32
40
  /** A harness bound to one identity; answers can/cannot for an `(op, table, row)`. */
33
41
  interface BoundPolicyAssertion {
34
42
  /**
35
- * Would this identity be **allowed** the operation on `row`?
36
- *
37
- * - `read` — is `row` visible? `true` when the table has no read policy (unrestricted), or when the effective read `baseWhere` matches `row`.
38
- * - `insert` — is the candidate `row` allowed by the insert policies?
39
- * - `update` / `delete` — is the pre-write `row` allowed? For `update` pass `nextRow` to also assert the post-image (WITH CHECK) — a policy can't be satisfied by the old row while the patch reassigns it to another tenant.
40
- *
41
- * A table with **no** policy in the list is unguarded → always `true`
42
- * (mirrors the middleware passing such tables through unwrapped). A table
43
- * that participates but declares no policy for the write `op` denies
44
- * (default-DENY), exactly as the middleware does.
45
- */
43
+ * Would this identity be **allowed** the operation on `row`?
44
+ *
45
+ * - `read` — is `row` visible? `true` when the table has no read policy (unrestricted), or when the effective read `baseWhere` matches `row`.
46
+ * - `insert` — is the candidate `row` allowed by the insert policies?
47
+ * - `update` / `delete` — is the pre-write `row` allowed? For `update` pass `nextRow` to also assert the post-image (WITH CHECK) — a policy can't be satisfied by the old row while the patch reassigns it to another tenant.
48
+ *
49
+ * A table with **no** policy in the list is unguarded → always `true`
50
+ * (mirrors the middleware passing such tables through unwrapped). A table
51
+ * that participates but declares no policy for the write `op` denies
52
+ * (default-DENY), exactly as the middleware does.
53
+ */
46
54
  can: (op: PolicyOperation, table: string, row?: Record<string, unknown>, nextRow?: Record<string, unknown>) => boolean;
47
55
  /** Negation of {@link BoundPolicyAssertion.can} — reads more naturally in a denial test. */
48
56
  cannot: (op: PolicyOperation, table: string, row?: Record<string, unknown>, nextRow?: Record<string, unknown>) => boolean;
@@ -53,11 +61,11 @@ interface PolicyAssertion {
53
61
  as: (identity?: TestIdentity | null) => BoundPolicyAssertion;
54
62
  }
55
63
  /**
56
- * Build an in-process assertion harness over a policy set. Reuses the `rls()`
57
- * middleware's own evaluation primitives, so an assertion is faithful to
58
- * request-time behaviour by construction.
59
- * @param policies the policy list, typically from `definePolicies([...])`.
60
- * @param options role registry + procedure `ctx` (see {@link ExpectPolicyOptions}).
61
- */
64
+ * Build an in-process assertion harness over a policy set. Reuses the `rls()`
65
+ * middleware's own evaluation primitives, so an assertion is faithful to
66
+ * request-time behaviour by construction.
67
+ * @param policies the policy list, typically from `definePolicies([...])`.
68
+ * @param options role registry + procedure `ctx` (see {@link ExpectPolicyOptions}).
69
+ */
62
70
  declare const expectPolicy: <Context = unknown>(policies: ReadonlyArray<Policy<Context>>, options?: ExpectPolicyOptions<Context>) => PolicyAssertion;
63
71
  export { BoundPolicyAssertion, ExpectPolicyOptions, PolicyAssertion, TestIdentity, expectPolicy };
@@ -1,48 +1,56 @@
1
- import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-BDY0FYHK.js";
1
+ import { P as PolicyOperation, R as Role, a as Policy } from "../packem_shared/types.d-BCtjbIzl.js";
2
2
  import "../data-model.js";
3
3
  /**
4
- * The slice of a request identity a policy reads. Mirrors the
5
- * `PolicyContext.auth` shape the middleware builds at request time — every
6
- * field is optional and defaults the same way the middleware defaults it
7
- * (`userId`/`identity` → `null`, `roles` → `[]`).
8
- */
4
+ * The slice of a request identity a policy reads. Mirrors the
5
+ * `PolicyContext.auth` shape the middleware builds at request time — every
6
+ * field is optional and defaults the same way the middleware defaults it
7
+ * (`userId`/`identity` → `null`, `roles` → the `roles` claim on `identity`).
8
+ *
9
+ * There is deliberately NO separate `roles` field: `auth.roles` is derived from
10
+ * the identity claims by the same `readIdentityRoles` the middleware uses, so
11
+ * the harness cannot set up a world the runtime is unable to produce. Give a
12
+ * role-branched policy its roles the way production does —
13
+ * `.as({ identity: { roles: ["admin"] }, userId: "u1" })`.
14
+ */
9
15
  interface TestIdentity {
10
- /** Raw identity claims a policy may branch on (`auth.identity.email`, …). */
16
+ /**
17
+ * Raw identity claims a policy may branch on (`auth.identity.email`, …).
18
+ * The `roles` claim (a `string[]` or a comma-separated string) is what
19
+ * populates `auth.roles` and backs `auth.can(...)`.
20
+ */
11
21
  identity?: Record<string, unknown> | null;
12
- /** Role labels the request carries; resolved to permissions via the harness `roles` registry. */
13
- roles?: ReadonlyArray<string>;
14
22
  /** The caller id (`auth.userId`); `null`/omitted is the anonymous caller. */
15
23
  userId?: null | string;
16
24
  }
17
25
  /** Options for {@link expectPolicy}. */
18
26
  interface ExpectPolicyOptions<Context = unknown> {
19
27
  /**
20
- * The procedure context a policy reads via `ctx` (e.g. `ctx.orgId`). Held
21
- * for the whole harness; pass a fresh `expectPolicy(..., { ctx })` for a
22
- * different context. Defaults to an empty object.
23
- */
28
+ * The procedure context a policy reads via `ctx` (e.g. `ctx.orgId`). Held
29
+ * for the whole harness; pass a fresh `expectPolicy(..., { ctx })` for a
30
+ * different context. Defaults to an empty object.
31
+ */
24
32
  ctx?: Context;
25
33
  /**
26
- * Role→permission grants backing `auth.can(...)` — the same registry passed
27
- * to `rls(policies, { roles })`. A role not listed here grants nothing, so
28
- * `can(...)` fails closed exactly as it does in production.
29
- */
34
+ * Role→permission grants backing `auth.can(...)` — the same registry passed
35
+ * to `rls(policies, { roles })`. A role not listed here grants nothing, so
36
+ * `can(...)` fails closed exactly as it does in production.
37
+ */
30
38
  roles?: ReadonlyArray<Role>;
31
39
  }
32
40
  /** A harness bound to one identity; answers can/cannot for an `(op, table, row)`. */
33
41
  interface BoundPolicyAssertion {
34
42
  /**
35
- * Would this identity be **allowed** the operation on `row`?
36
- *
37
- * - `read` — is `row` visible? `true` when the table has no read policy (unrestricted), or when the effective read `baseWhere` matches `row`.
38
- * - `insert` — is the candidate `row` allowed by the insert policies?
39
- * - `update` / `delete` — is the pre-write `row` allowed? For `update` pass `nextRow` to also assert the post-image (WITH CHECK) — a policy can't be satisfied by the old row while the patch reassigns it to another tenant.
40
- *
41
- * A table with **no** policy in the list is unguarded → always `true`
42
- * (mirrors the middleware passing such tables through unwrapped). A table
43
- * that participates but declares no policy for the write `op` denies
44
- * (default-DENY), exactly as the middleware does.
45
- */
43
+ * Would this identity be **allowed** the operation on `row`?
44
+ *
45
+ * - `read` — is `row` visible? `true` when the table has no read policy (unrestricted), or when the effective read `baseWhere` matches `row`.
46
+ * - `insert` — is the candidate `row` allowed by the insert policies?
47
+ * - `update` / `delete` — is the pre-write `row` allowed? For `update` pass `nextRow` to also assert the post-image (WITH CHECK) — a policy can't be satisfied by the old row while the patch reassigns it to another tenant.
48
+ *
49
+ * A table with **no** policy in the list is unguarded → always `true`
50
+ * (mirrors the middleware passing such tables through unwrapped). A table
51
+ * that participates but declares no policy for the write `op` denies
52
+ * (default-DENY), exactly as the middleware does.
53
+ */
46
54
  can: (op: PolicyOperation, table: string, row?: Record<string, unknown>, nextRow?: Record<string, unknown>) => boolean;
47
55
  /** Negation of {@link BoundPolicyAssertion.can} — reads more naturally in a denial test. */
48
56
  cannot: (op: PolicyOperation, table: string, row?: Record<string, unknown>, nextRow?: Record<string, unknown>) => boolean;
@@ -53,11 +61,11 @@ interface PolicyAssertion {
53
61
  as: (identity?: TestIdentity | null) => BoundPolicyAssertion;
54
62
  }
55
63
  /**
56
- * Build an in-process assertion harness over a policy set. Reuses the `rls()`
57
- * middleware's own evaluation primitives, so an assertion is faithful to
58
- * request-time behaviour by construction.
59
- * @param policies the policy list, typically from `definePolicies([...])`.
60
- * @param options role registry + procedure `ctx` (see {@link ExpectPolicyOptions}).
61
- */
64
+ * Build an in-process assertion harness over a policy set. Reuses the `rls()`
65
+ * middleware's own evaluation primitives, so an assertion is faithful to
66
+ * request-time behaviour by construction.
67
+ * @param policies the policy list, typically from `definePolicies([...])`.
68
+ * @param options role registry + procedure `ctx` (see {@link ExpectPolicyOptions}).
69
+ */
62
70
  declare const expectPolicy: <Context = unknown>(policies: ReadonlyArray<Policy<Context>>, options?: ExpectPolicyOptions<Context>) => PolicyAssertion;
63
71
  export { BoundPolicyAssertion, ExpectPolicyOptions, PolicyAssertion, TestIdentity, expectPolicy };
@@ -1,49 +1 @@
1
- import { indexRolePermissions, computeReadBaseWhere, matchesWhere, evaluateWrite, permissionName } from '../packem_shared/rls-BDKRbMCA.mjs';
2
-
3
- const expectPolicy = (policies, options = {}) => {
4
- const rolePermissions = indexRolePermissions(options.roles);
5
- const context = options.ctx ?? {};
6
- return {
7
- as: (identity) => {
8
- const auth = identity ?? {};
9
- const roles = auth.roles ?? [];
10
- const granted = /* @__PURE__ */ new Set();
11
- for (const roleName of roles) {
12
- for (const name of rolePermissions.get(roleName) ?? []) {
13
- granted.add(name);
14
- }
15
- }
16
- const baseContext = {
17
- auth: {
18
- can: (permission) => granted.has(permissionName(permission)),
19
- // eslint-disable-next-line unicorn/no-null -- PolicyContext.auth.identity is a public `… | null` type, mirroring the middleware
20
- identity: auth.identity ?? null,
21
- roles,
22
- // eslint-disable-next-line unicorn/no-null -- PolicyContext.auth.userId is a public `null | string` type, mirroring the middleware
23
- userId: auth.userId ?? null
24
- },
25
- ctx: context
26
- };
27
- const can = (op, table, row, nextRow) => {
28
- const tablePolicies = policies.filter((policy) => policy.table === table);
29
- if (tablePolicies.length === 0) {
30
- return true;
31
- }
32
- if (op === "read") {
33
- if (!tablePolicies.some((policy) => policy.on === "read")) {
34
- return true;
35
- }
36
- const baseWhere = computeReadBaseWhere(tablePolicies, baseContext);
37
- return baseWhere === void 0 || matchesWhere(row ?? {}, baseWhere);
38
- }
39
- return evaluateWrite(tablePolicies, op, { ...baseContext, row }, nextRow);
40
- };
41
- return {
42
- can,
43
- cannot: (op, table, row, nextRow) => !can(op, table, row, nextRow)
44
- };
45
- }
46
- };
47
- };
48
-
49
- export { expectPolicy };
1
+ import{i as y,e as P,g as W,f as v,m as I,h as R}from"../packem_shared/middleware-DbhB1jRk.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};