@axiom-lattice/local-stores 5.0.2 → 5.1.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@axiom-lattice/local-stores",
3
- "version": "5.0.2",
3
+ "version": "5.1.0",
4
4
  "description": "Local SQLite-based stores for Axiom Lattice framework",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -25,8 +25,8 @@
25
25
  "@types/sql.js": "^1.4.11",
26
26
  "sql.js": "^1.14.1",
27
27
  "uuid": "^14.0.1",
28
- "@axiom-lattice/core": "12.1.0",
29
- "@axiom-lattice/protocols": "7.1.0"
28
+ "@axiom-lattice/core": "12.2.0",
29
+ "@axiom-lattice/protocols": "7.2.0"
30
30
  },
31
31
  "devDependencies": {
32
32
  "@types/jest": "^29.5.14",
@@ -0,0 +1,48 @@
1
+ import { afterEach, describe, expect, it } from "@jest/globals";
2
+ import { existsSync, unlinkSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { closeDatabase, initDatabase, type DatabaseWrapper } from "../database";
6
+ import { LocalInviteLinkStore } from "../stores/LocalInviteLinkStore";
7
+
8
+ const nextDbPath = () =>
9
+ path.join(tmpdir(), `lt-invite-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
10
+
11
+ describe("LocalInviteLinkStore", () => {
12
+ let dbPath: string;
13
+ let db: DatabaseWrapper;
14
+ afterEach(() => {
15
+ closeDatabase();
16
+ if (dbPath && existsSync(dbPath)) unlinkSync(dbPath);
17
+ });
18
+ async function setup() {
19
+ dbPath = nextDbPath();
20
+ db = await initDatabase({ dbPath });
21
+ return new LocalInviteLinkStore(db);
22
+ }
23
+ it("persists an encrypted token and consumes one use atomically", async () => {
24
+ const store = await setup();
25
+ const created = await store.create({
26
+ id: "link-1",
27
+ scope: "tenant",
28
+ token: "secret-token",
29
+ tokenHash: "hash-1",
30
+ email: "User@Example.com",
31
+ tenantId: "tenant-1",
32
+ tenantRole: "member",
33
+ expiresAt: new Date("2030-01-01T00:00:00.000Z"),
34
+ maxUses: 1,
35
+ });
36
+ expect(created.email).toBe("user@example.com");
37
+ await expect(store.getByTokenHash("hash-1")).resolves.toMatchObject({
38
+ token: "secret-token",
39
+ usedCount: 0,
40
+ });
41
+ await expect(
42
+ store.consume("hash-1", new Date("2026-01-01T00:00:00.000Z")),
43
+ ).resolves.toMatchObject({ usedCount: 1 });
44
+ await expect(
45
+ store.consume("hash-1", new Date("2026-01-01T00:00:00.000Z")),
46
+ ).resolves.toBeNull();
47
+ });
48
+ });
@@ -0,0 +1,114 @@
1
+ import { afterEach, describe, expect, it } from "@jest/globals";
2
+ import { existsSync, unlinkSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import {
6
+ OidcIdentityClaimConflictError,
7
+ type CreateOidcIdentityClaimInput,
8
+ } from "@axiom-lattice/protocols";
9
+ import { closeDatabase, initDatabase, type DatabaseWrapper } from "../database";
10
+ import { LocalOidcIdentityClaimStore } from "../stores/LocalOidcIdentityClaimStore";
11
+
12
+ const NOW = new Date("2026-01-01T00:00:00.000Z");
13
+
14
+ function input(
15
+ overrides: Partial<CreateOidcIdentityClaimInput> = {},
16
+ ): CreateOidcIdentityClaimInput {
17
+ return {
18
+ id: "claim-1",
19
+ providerId: "logto",
20
+ issuer: "https://idp.example.com/oidc",
21
+ subject: "subject-1",
22
+ email: "User@Example.com",
23
+ name: "User",
24
+ expiresAt: new Date("2030-01-08T00:00:00.000Z"),
25
+ ...overrides,
26
+ };
27
+ }
28
+
29
+ const nextDbPath = () =>
30
+ path.join(
31
+ tmpdir(),
32
+ `lt-oidc-claim-${Date.now()}-${Math.random().toString(36).slice(2)}.db`,
33
+ );
34
+
35
+ describe("LocalOidcIdentityClaimStore", () => {
36
+ let dbPath: string;
37
+ let db: DatabaseWrapper;
38
+
39
+ afterEach(() => {
40
+ closeDatabase();
41
+ if (dbPath && existsSync(dbPath)) unlinkSync(dbPath);
42
+ });
43
+
44
+ async function setup(): Promise<LocalOidcIdentityClaimStore> {
45
+ dbPath = nextDbPath();
46
+ db = await initDatabase({ dbPath });
47
+ return new LocalOidcIdentityClaimStore(db);
48
+ }
49
+
50
+ it("creates and finds a pending claim", async () => {
51
+ const store = await setup();
52
+ const claim = await store.create(input());
53
+
54
+ expect(claim).toMatchObject({
55
+ id: "claim-1",
56
+ email: "user@example.com",
57
+ status: "pending",
58
+ });
59
+ await expect(
60
+ store.getPendingBySubject(
61
+ "logto",
62
+ "https://idp.example.com/oidc",
63
+ "subject-1",
64
+ NOW,
65
+ ),
66
+ ).resolves.toMatchObject({ id: "claim-1" });
67
+ });
68
+
69
+ it("rejects a duplicate live pending claim", async () => {
70
+ const store = await setup();
71
+ await store.create(input());
72
+ await expect(store.create(input({ id: "claim-2" }))).rejects.toBeInstanceOf(
73
+ OidcIdentityClaimConflictError,
74
+ );
75
+ });
76
+
77
+ it("allows a retry after the previous pending claim expired", async () => {
78
+ const store = await setup();
79
+ await store.create(
80
+ input({
81
+ id: "claim-old",
82
+ subject: "subject-old",
83
+ expiresAt: new Date("2025-12-31T00:00:00.000Z"),
84
+ }),
85
+ );
86
+ await expect(
87
+ store.create(input({ id: "claim-new", subject: "subject-old" })),
88
+ ).resolves.toMatchObject({ id: "claim-new" });
89
+ expect(await store.list("expired")).toHaveLength(1);
90
+ });
91
+
92
+ it("updates, approves, and rejects with CAS", async () => {
93
+ const store = await setup();
94
+ await store.create(input());
95
+
96
+ await expect(
97
+ store.updatePending("claim-1", { email: "new@example.com" }, NOW),
98
+ ).resolves.toMatchObject({ email: "new@example.com" });
99
+ await expect(
100
+ store.approve(
101
+ "claim-1",
102
+ { reviewedBy: "admin-1", linkedUserId: "user-1" },
103
+ NOW,
104
+ ),
105
+ ).resolves.toMatchObject({
106
+ status: "approved",
107
+ linkedUserId: "user-1",
108
+ });
109
+ await expect(
110
+ store.updatePending("claim-1", { email: "late@example.com" }, NOW),
111
+ ).resolves.toBeNull();
112
+ await expect(store.reject("claim-1", "admin-2", NOW)).resolves.toBeNull();
113
+ });
114
+ });
@@ -0,0 +1,203 @@
1
+ import { afterEach, describe, expect, it } from "@jest/globals";
2
+ import { existsSync, unlinkSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import { decrypt } from "@axiom-lattice/core";
6
+ import {
7
+ OidcProviderConfigConflictError,
8
+ type CreateOidcProviderConfigInput,
9
+ } from "@axiom-lattice/protocols";
10
+ import { closeDatabase, initDatabase, type DatabaseWrapper } from "../database";
11
+ import { LocalOidcProviderConfigStore } from "../stores/LocalOidcProviderConfigStore";
12
+
13
+ process.env.LATTICE_ENCRYPTION_KEY ??= "test-oidc-encryption-key";
14
+
15
+ const input: CreateOidcProviderConfigInput = {
16
+ displayName: "Contoso Entra",
17
+ issuer: "https://login.microsoftonline.com/tenant-id/v2.0",
18
+ clientId: "client-id",
19
+ clientSecret: "super-secret",
20
+ scopes: "openid profile email",
21
+ enabled: true,
22
+ jitProvisioning: true,
23
+ autoLinkEmail: false,
24
+ defaultTenantId: "tenant-1",
25
+ };
26
+
27
+ const nextDbPath = () =>
28
+ path.join(tmpdir(), `lt-oidc-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
29
+
30
+ describe("LocalOidcProviderConfigStore", () => {
31
+ let dbPath: string;
32
+ let db: DatabaseWrapper;
33
+
34
+ afterEach(() => {
35
+ closeDatabase();
36
+ if (dbPath && existsSync(dbPath)) unlinkSync(dbPath);
37
+ });
38
+
39
+ async function setup(): Promise<LocalOidcProviderConfigStore> {
40
+ dbPath = nextDbPath();
41
+ db = await initDatabase({ dbPath });
42
+ return new LocalOidcProviderConfigStore(db);
43
+ }
44
+
45
+ it("creates, reads and lists provider configs by created_at", async () => {
46
+ const store = await setup();
47
+ const created = await store.create("alpha", input);
48
+
49
+ expect(created).toMatchObject({ id: "alpha", ...input });
50
+ expect(created.createdAt).toBeInstanceOf(Date);
51
+ expect(created.updatedAt).toBeInstanceOf(Date);
52
+
53
+ await store.create("mike", { ...input, displayName: "Mike" });
54
+ await store.create("zulu", { ...input, displayName: "Zulu" });
55
+
56
+ // Make created_at order intentionally differ from both insertion and
57
+ // alphabetical id order.
58
+ const timestamps: Record<string, string> = {
59
+ zulu: "2020-01-01T00:00:01.000Z",
60
+ alpha: "2020-01-01T00:00:02.000Z",
61
+ mike: "2020-01-01T00:00:03.000Z",
62
+ };
63
+ for (const [id, createdAt] of Object.entries(timestamps)) {
64
+ db.prepare(
65
+ "UPDATE lattice_oidc_provider_configs SET created_at = ? WHERE id = ?",
66
+ ).run(createdAt, id);
67
+ }
68
+
69
+ const listed = await store.list();
70
+ expect(listed.map((item) => item.id)).toEqual(["zulu", "alpha", "mike"]);
71
+ await expect(store.get("missing")).resolves.toBeNull();
72
+ });
73
+
74
+ it("returns an empty secret for undecryptable ciphertext without crashing", async () => {
75
+ const store = await setup();
76
+ await store.create("corrupt", input);
77
+
78
+ const corrupt = Buffer.alloc(80, 7).toString("base64");
79
+ db.prepare(
80
+ "UPDATE lattice_oidc_provider_configs SET client_secret = ? WHERE id = ?",
81
+ ).run(corrupt, "corrupt");
82
+
83
+ await expect(store.get("corrupt")).resolves.toMatchObject({
84
+ id: "corrupt",
85
+ clientSecret: "",
86
+ });
87
+ const listed = await store.list();
88
+ expect(listed).toHaveLength(1);
89
+ expect(listed[0].clientSecret).toBe("");
90
+ });
91
+
92
+ it("encrypts the client secret at rest and decrypts it on read", async () => {
93
+ const store = await setup();
94
+ await store.create("contoso", input);
95
+
96
+ const row = db
97
+ .prepare(
98
+ "SELECT client_secret FROM lattice_oidc_provider_configs WHERE id = ?",
99
+ )
100
+ .get("contoso") as { client_secret: string };
101
+
102
+ expect(row.client_secret).not.toBe("super-secret");
103
+ expect(decrypt(row.client_secret)).toBe("super-secret");
104
+ await expect(store.get("contoso")).resolves.toMatchObject({
105
+ clientSecret: "super-secret",
106
+ });
107
+
108
+ });
109
+
110
+ it("updates fields, preserves secrets and rejects duplicate ids", async () => {
111
+ const store = await setup();
112
+ await store.create("contoso", input);
113
+
114
+ await expect(store.create("contoso", input)).rejects.toBeInstanceOf(
115
+ OidcProviderConfigConflictError,
116
+ );
117
+
118
+ const omitted = await store.update("contoso", {
119
+ displayName: "Contoso Updated",
120
+ enabled: false,
121
+ defaultTenantId: null,
122
+ });
123
+ expect(omitted).toMatchObject({
124
+ id: "contoso",
125
+ displayName: "Contoso Updated",
126
+ enabled: false,
127
+ clientSecret: "super-secret",
128
+ });
129
+ expect(omitted?.defaultTenantId).toBeUndefined();
130
+
131
+ const empty = await store.update("contoso", { clientSecret: "" });
132
+ expect(empty?.clientSecret).toBe("super-secret");
133
+
134
+ const replaced = await store.update("contoso", {
135
+ clientSecret: "next-secret",
136
+ scopes: "openid email",
137
+ });
138
+ expect(replaced).toMatchObject({
139
+ clientSecret: "next-secret",
140
+ scopes: "openid email",
141
+ });
142
+
143
+ // Replaced secret is encrypted at rest.
144
+ const row = db
145
+ .prepare(
146
+ "SELECT client_secret FROM lattice_oidc_provider_configs WHERE id = ?",
147
+ )
148
+ .get("contoso") as { client_secret: string };
149
+ expect(row.client_secret).not.toBe("next-secret");
150
+ expect(decrypt(row.client_secret)).toBe("next-secret");
151
+
152
+ await expect(store.update("missing", { enabled: false })).resolves.toBeNull();
153
+ });
154
+
155
+ it("round-trips undefined and empty allowedPrivateHosts distinctly", async () => {
156
+ const store = await setup();
157
+ const createdUndefined = await store.create("undefined", input);
158
+ expect(createdUndefined.allowedPrivateHosts).toBeUndefined();
159
+ const rawUndefined = db
160
+ .prepare(
161
+ "SELECT allowed_private_hosts FROM lattice_oidc_provider_configs WHERE id = ?",
162
+ )
163
+ .get("undefined") as { allowed_private_hosts: string | null };
164
+ expect(rawUndefined.allowed_private_hosts).toBeNull();
165
+
166
+ const createdEmpty = await store.create("empty", {
167
+ ...input,
168
+ allowedPrivateHosts: [],
169
+ });
170
+ expect(createdEmpty.allowedPrivateHosts).toEqual([]);
171
+ const rawEmpty = db
172
+ .prepare(
173
+ "SELECT allowed_private_hosts FROM lattice_oidc_provider_configs WHERE id = ?",
174
+ )
175
+ .get("empty") as { allowed_private_hosts: string | null };
176
+ expect(rawEmpty.allowed_private_hosts).toBe("[]");
177
+ await expect(store.get("empty")).resolves.toMatchObject({
178
+ allowedPrivateHosts: [],
179
+ });
180
+
181
+ await store.create("list", {
182
+ ...input,
183
+ allowedPrivateHosts: ["internal-idp.example.com"],
184
+ });
185
+ await expect(store.get("list")).resolves.toMatchObject({
186
+ allowedPrivateHosts: ["internal-idp.example.com"],
187
+ });
188
+ const cleared = await store.update("list", { allowedPrivateHosts: [] });
189
+ expect(cleared?.allowedPrivateHosts).toEqual([]);
190
+ await expect(store.get("list")).resolves.toMatchObject({
191
+ allowedPrivateHosts: [],
192
+ });
193
+ });
194
+
195
+ it("deletes provider configs", async () => {
196
+ const store = await setup();
197
+ await store.create("contoso", input);
198
+
199
+ await expect(store.delete("contoso")).resolves.toBe(true);
200
+ await expect(store.get("contoso")).resolves.toBeNull();
201
+ await expect(store.delete("contoso")).resolves.toBe(false);
202
+ });
203
+ });
@@ -0,0 +1,207 @@
1
+ import { afterEach, describe, expect, it } from "@jest/globals";
2
+ import { existsSync, unlinkSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
5
+ import type { PlatformInvitation } from "@axiom-lattice/protocols";
6
+ import { closeDatabase, initDatabase, type DatabaseWrapper } from "../database";
7
+ import { LocalPlatformInvitationStore } from "../stores/LocalPlatformInvitationStore";
8
+
9
+ function invitation(
10
+ email: string,
11
+ overrides: Partial<PlatformInvitation> = {},
12
+ ): PlatformInvitation {
13
+ return {
14
+ email,
15
+ role: "admin",
16
+ invitedBy: "owner-1",
17
+ createdAt: new Date("2026-01-01T00:00:00.000Z"),
18
+ ...overrides,
19
+ };
20
+ }
21
+
22
+ const nextDbPath = () =>
23
+ path.join(
24
+ tmpdir(),
25
+ `lt-platform-invitation-${Date.now()}-${Math.random().toString(36).slice(2)}.db`,
26
+ );
27
+
28
+ describe("LocalPlatformInvitationStore", () => {
29
+ let dbPath: string;
30
+ let db: DatabaseWrapper;
31
+
32
+ afterEach(() => {
33
+ closeDatabase();
34
+ if (dbPath && existsSync(dbPath)) unlinkSync(dbPath);
35
+ });
36
+
37
+ async function setup(): Promise<LocalPlatformInvitationStore> {
38
+ dbPath = nextDbPath();
39
+ db = await initDatabase({ dbPath });
40
+ return new LocalPlatformInvitationStore(db);
41
+ }
42
+
43
+ it("upserts, reads and lists invitations by normalized email", async () => {
44
+ const store = await setup();
45
+
46
+ await store.upsert(invitation("bob@example.com", { role: "auditor" }));
47
+ await store.upsert(invitation("alice@example.com", { role: "owner" }));
48
+
49
+ await expect(store.get("alice@example.com")).resolves.toMatchObject({
50
+ email: "alice@example.com",
51
+ role: "owner",
52
+ invitedBy: "owner-1",
53
+ });
54
+ await expect(store.get("missing@example.com")).resolves.toBeNull();
55
+
56
+ const listed = await store.list();
57
+ expect(listed.map((entry) => entry.email)).toEqual([
58
+ "alice@example.com",
59
+ "bob@example.com",
60
+ ]);
61
+ });
62
+
63
+ it("normalizes email on writes and lookups", async () => {
64
+ const store = await setup();
65
+
66
+ await store.upsert(invitation(" Alice@Example.COM "));
67
+
68
+ await expect(store.get("alice@example.com")).resolves.toMatchObject({
69
+ email: "alice@example.com",
70
+ });
71
+ await expect(store.get(" ALICE@example.com ")).resolves.toMatchObject({
72
+ email: "alice@example.com",
73
+ });
74
+ const listed = await store.list();
75
+ expect(listed).toHaveLength(1);
76
+ expect(listed[0]?.email).toBe("alice@example.com");
77
+ });
78
+
79
+ it("replaces duplicates with last-write-wins semantics", async () => {
80
+ const store = await setup();
81
+ await store.upsert(invitation("alice@example.com", { role: "admin" }));
82
+
83
+ const updated = await store.upsert(
84
+ invitation(" ALICE@example.com ", {
85
+ role: "owner",
86
+ invitedBy: "owner-2",
87
+ createdAt: new Date("2026-02-01T00:00:00.000Z"),
88
+ expiresAt: new Date("2026-03-01T00:00:00.000Z"),
89
+ }),
90
+ );
91
+
92
+ expect(updated).toMatchObject({
93
+ email: "alice@example.com",
94
+ role: "owner",
95
+ invitedBy: "owner-2",
96
+ });
97
+ await expect(store.list()).resolves.toHaveLength(1);
98
+ await expect(store.get("alice@example.com")).resolves.toMatchObject({
99
+ role: "owner",
100
+ invitedBy: "owner-2",
101
+ });
102
+
103
+ const row = db
104
+ .prepare(
105
+ "SELECT email, role, invited_by FROM lattice_platform_invitations WHERE email = ?",
106
+ )
107
+ .get("alice@example.com") as {
108
+ email: string;
109
+ role: string;
110
+ invited_by: string;
111
+ };
112
+ expect(row).toEqual({
113
+ email: "alice@example.com",
114
+ role: "owner",
115
+ invited_by: "owner-2",
116
+ });
117
+ });
118
+
119
+ it("consumes pending unexpired invitations atomically", async () => {
120
+ const store = await setup();
121
+ const at = new Date("2026-02-01T00:00:00.000Z");
122
+ await store.upsert(
123
+ invitation("alice@example.com", {
124
+ expiresAt: new Date("2026-03-01T00:00:00.000Z"),
125
+ }),
126
+ );
127
+
128
+ const consumed = await store.consume(" ALICE@example.com ", at);
129
+
130
+ expect(consumed).toMatchObject({
131
+ email: "alice@example.com",
132
+ consumedAt: at,
133
+ });
134
+ await expect(store.get("alice@example.com")).resolves.toMatchObject({
135
+ consumedAt: at,
136
+ });
137
+ });
138
+
139
+ it("does not consume an already-consumed invitation", async () => {
140
+ const store = await setup();
141
+ const first = new Date("2026-02-01T00:00:00.000Z");
142
+ const second = new Date("2026-02-02T00:00:00.000Z");
143
+ await store.upsert(invitation("alice@example.com"));
144
+
145
+ await expect(store.consume("alice@example.com", first)).resolves.toMatchObject({
146
+ consumedAt: first,
147
+ });
148
+ await expect(store.consume("alice@example.com", second)).resolves.toBeNull();
149
+ await expect(store.get("alice@example.com")).resolves.toMatchObject({
150
+ consumedAt: first,
151
+ });
152
+ });
153
+
154
+ it("does not consume an expired invitation", async () => {
155
+ const store = await setup();
156
+ const expiresAt = new Date("2026-02-01T00:00:00.000Z");
157
+ await store.upsert(invitation("alice@example.com", { expiresAt }));
158
+
159
+ await expect(
160
+ store.consume("alice@example.com", new Date("2026-02-01T00:00:00.000Z")),
161
+ ).resolves.toBeNull();
162
+ await expect(
163
+ store.consume("alice@example.com", new Date("2026-01-31T23:59:59.000Z")),
164
+ ).resolves.toMatchObject({
165
+ consumedAt: new Date("2026-01-31T23:59:59.000Z"),
166
+ });
167
+ });
168
+
169
+ it("returns null when consuming a missing invitation", async () => {
170
+ const store = await setup();
171
+ await expect(store.consume("missing@example.com", new Date())).resolves.toBeNull();
172
+ });
173
+
174
+ it("deletes invitations", async () => {
175
+ const store = await setup();
176
+ await store.upsert(invitation("alice@example.com"));
177
+
178
+ await expect(store.delete(" ALICE@example.com ")).resolves.toBe(true);
179
+ await expect(store.get("alice@example.com")).resolves.toBeNull();
180
+ await expect(store.delete("alice@example.com")).resolves.toBe(false);
181
+ });
182
+
183
+ it("omits optional fields when they are not provided", async () => {
184
+ const store = await setup();
185
+ const { invitedBy: _invitedBy, ...withoutInvitedBy } = invitation("alice@example.com");
186
+
187
+ await store.upsert(withoutInvitedBy);
188
+
189
+ const stored = await store.get("alice@example.com");
190
+ expect(stored?.invitedBy).toBeUndefined();
191
+ expect(stored?.expiresAt).toBeUndefined();
192
+ expect(stored?.consumedAt).toBeUndefined();
193
+ });
194
+
195
+ it("round-trips timestamps", async () => {
196
+ const store = await setup();
197
+ const createdAt = new Date("2026-03-04T05:06:07.000Z");
198
+ const expiresAt = new Date("2026-04-05T06:07:08.000Z");
199
+
200
+ await store.upsert(invitation("alice@example.com", { createdAt, expiresAt }));
201
+
202
+ const stored = await store.get("alice@example.com");
203
+ expect(stored?.createdAt).toBeInstanceOf(Date);
204
+ expect(stored?.createdAt.getTime()).toBe(createdAt.getTime());
205
+ expect(stored?.expiresAt?.getTime()).toBe(expiresAt.getTime());
206
+ });
207
+ });