@axiom-lattice/local-stores 5.0.3 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,123 @@
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 { PlatformMember } from "@axiom-lattice/protocols";
6
+ import { closeDatabase, initDatabase, type DatabaseWrapper } from "../database";
7
+ import { LocalPlatformMemberStore } from "../stores/LocalPlatformMemberStore";
8
+
9
+ function member(
10
+ userId: string,
11
+ overrides: Partial<PlatformMember> = {},
12
+ ): PlatformMember {
13
+ return {
14
+ userId,
15
+ role: "admin",
16
+ grantedBy: "owner-1",
17
+ grantedAt: new Date("2026-01-01T00:00:00.000Z"),
18
+ updatedAt: new Date("2026-01-01T00:00:00.000Z"),
19
+ ...overrides,
20
+ };
21
+ }
22
+
23
+ const nextDbPath = () =>
24
+ path.join(tmpdir(), `lt-platform-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
25
+
26
+ describe("LocalPlatformMemberStore", () => {
27
+ let dbPath: string;
28
+ let db: DatabaseWrapper;
29
+
30
+ afterEach(() => {
31
+ closeDatabase();
32
+ if (dbPath && existsSync(dbPath)) unlinkSync(dbPath);
33
+ });
34
+
35
+ async function setup(): Promise<LocalPlatformMemberStore> {
36
+ dbPath = nextDbPath();
37
+ db = await initDatabase({ dbPath });
38
+ return new LocalPlatformMemberStore(db);
39
+ }
40
+
41
+ it("upserts, reads and lists platform members by user id", async () => {
42
+ const store = await setup();
43
+
44
+ await store.upsert(member("user-b", { role: "auditor" }));
45
+ await store.upsert(member("user-a", { role: "owner" }));
46
+
47
+ await expect(store.get("user-a")).resolves.toMatchObject({
48
+ userId: "user-a",
49
+ role: "owner",
50
+ grantedBy: "owner-1",
51
+ });
52
+ await expect(store.get("missing")).resolves.toBeNull();
53
+
54
+ const listed = await store.list();
55
+ expect(listed.map((entry) => entry.userId)).toEqual(["user-a", "user-b"]);
56
+ expect(listed.map((entry) => entry.role)).toEqual(["owner", "auditor"]);
57
+ });
58
+
59
+ it("persists role changes with last-write-wins semantics", async () => {
60
+ const store = await setup();
61
+ await store.upsert(member("user-1", { role: "admin" }));
62
+
63
+ const updated = await store.upsert(
64
+ member("user-1", {
65
+ role: "owner",
66
+ grantedBy: "owner-2",
67
+ grantedAt: new Date("2026-02-01T00:00:00.000Z"),
68
+ updatedAt: new Date("2026-02-01T00:00:00.000Z"),
69
+ }),
70
+ );
71
+
72
+ expect(updated).toMatchObject({
73
+ userId: "user-1",
74
+ role: "owner",
75
+ grantedBy: "owner-2",
76
+ });
77
+ await expect(store.get("user-1")).resolves.toMatchObject({
78
+ role: "owner",
79
+ grantedBy: "owner-2",
80
+ });
81
+ await expect(store.list()).resolves.toHaveLength(1);
82
+
83
+ const row = db
84
+ .prepare(
85
+ "SELECT role, granted_by FROM lattice_platform_members WHERE user_id = ?",
86
+ )
87
+ .get("user-1") as { role: string; granted_by: string };
88
+ expect(row).toEqual({ role: "owner", granted_by: "owner-2" });
89
+ });
90
+
91
+ it("round-trips grant and update timestamps", async () => {
92
+ const store = await setup();
93
+ const grantedAt = new Date("2026-03-04T05:06:07.000Z");
94
+ const updatedAt = new Date("2026-03-05T06:07:08.000Z");
95
+
96
+ await store.upsert(member("user-1", { grantedAt, updatedAt }));
97
+
98
+ const stored = await store.get("user-1");
99
+ expect(stored?.grantedAt).toBeInstanceOf(Date);
100
+ expect(stored?.grantedAt.getTime()).toBe(grantedAt.getTime());
101
+ expect(stored?.updatedAt).toBeInstanceOf(Date);
102
+ expect(stored?.updatedAt.getTime()).toBe(updatedAt.getTime());
103
+ });
104
+
105
+ it("omits grantedBy when it is not provided", async () => {
106
+ const store = await setup();
107
+ const { grantedBy: _grantedBy, ...withoutGrantedBy } = member("user-1");
108
+
109
+ await store.upsert(withoutGrantedBy);
110
+
111
+ const stored = await store.get("user-1");
112
+ expect(stored?.grantedBy).toBeUndefined();
113
+ });
114
+
115
+ it("deletes members", async () => {
116
+ const store = await setup();
117
+ await store.upsert(member("user-1"));
118
+
119
+ await expect(store.delete("user-1")).resolves.toBe(true);
120
+ await expect(store.get("user-1")).resolves.toBeNull();
121
+ await expect(store.delete("user-1")).resolves.toBe(false);
122
+ });
123
+ });
@@ -0,0 +1,120 @@
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 { LocalPlatformSettingsStore } from "../stores/LocalPlatformSettingsStore";
7
+
8
+ const nextDbPath = () =>
9
+ path.join(
10
+ tmpdir(),
11
+ `lt-platform-settings-${Date.now()}-${Math.random().toString(36).slice(2)}.db`,
12
+ );
13
+
14
+ describe("LocalPlatformSettingsStore", () => {
15
+ let dbPath: string;
16
+ let db: DatabaseWrapper;
17
+ afterEach(() => {
18
+ closeDatabase();
19
+ if (dbPath && existsSync(dbPath)) unlinkSync(dbPath);
20
+ });
21
+
22
+ async function setup() {
23
+ dbPath = nextDbPath();
24
+ db = await initDatabase({ dbPath });
25
+ return new LocalPlatformSettingsStore(db);
26
+ }
27
+
28
+ it("returns null before anything is saved", async () => {
29
+ const store = await setup();
30
+ await expect(store.get()).resolves.toBeNull();
31
+ });
32
+
33
+ it("persists JSON and enforces CAS", async () => {
34
+ const store = await setup();
35
+ const first = await store.save(
36
+ { invite: { defaultMaxUses: 3 } },
37
+ 0,
38
+ "admin-1",
39
+ );
40
+ expect(first.version).toBe(1);
41
+ expect(first.invite).toEqual({ defaultMaxUses: 3 });
42
+ expect(first.updatedBy).toBe("admin-1");
43
+ expect(first.updatedAt).toBeInstanceOf(Date);
44
+
45
+ await expect(
46
+ store.save({ invite: { defaultMaxUses: 4 } }, 0, "admin-2"),
47
+ ).rejects.toMatchObject({
48
+ code: "PLATFORM_SETTINGS_VERSION_CONFLICT",
49
+ actualVersion: 1,
50
+ });
51
+ });
52
+
53
+ it("increments version and replaces the full document", async () => {
54
+ const store = await setup();
55
+ await store.save({ invite: { defaultMaxUses: 3 } }, 0, "admin-1");
56
+ const second = await store.save(
57
+ { auth: { emailCompletionEnabled: false } },
58
+ 1,
59
+ "admin-2",
60
+ );
61
+ expect(second.version).toBe(2);
62
+ expect(second.auth).toEqual({ emailCompletionEnabled: false });
63
+ expect(second.invite).toBeUndefined();
64
+
65
+ const reloaded = await store.get();
66
+ expect(reloaded).toMatchObject({
67
+ version: 2,
68
+ auth: { emailCompletionEnabled: false },
69
+ updatedBy: "admin-2",
70
+ });
71
+ expect(reloaded?.updatedAt).toBeInstanceOf(Date);
72
+ });
73
+
74
+ it("omits empty and whitespace-only updatedBy", async () => {
75
+ const store = await setup();
76
+ const first = await store.save({ invite: { defaultMaxUses: 2 } }, 0, " ");
77
+ expect(first.updatedBy).toBeUndefined();
78
+ expect((await store.get())?.updatedBy).toBeUndefined();
79
+
80
+ const second = await store.save({ invite: { defaultMaxUses: 3 } }, 1, "");
81
+ expect(second.updatedBy).toBeUndefined();
82
+ });
83
+
84
+ it("rejects an update against a stale version without writing", async () => {
85
+ const store = await setup();
86
+ await store.save({ invite: { defaultMaxUses: 3 } }, 0, "admin-1");
87
+
88
+ await expect(
89
+ store.save({ invite: { defaultMaxUses: 9 } }, 5, "admin-2"),
90
+ ).rejects.toMatchObject({
91
+ code: "PLATFORM_SETTINGS_VERSION_CONFLICT",
92
+ actualVersion: 1,
93
+ });
94
+
95
+ await expect(store.get()).resolves.toMatchObject({
96
+ version: 1,
97
+ invite: { defaultMaxUses: 3 },
98
+ });
99
+ });
100
+
101
+ it("preserves explicit false, null, and empty structures", async () => {
102
+ const store = await setup();
103
+ const saved = await store.save(
104
+ {
105
+ auth: { emailCompletionEnabled: false },
106
+ invite: {},
107
+ rateLimits: { maxActiveRunTasksPerTenant: null },
108
+ },
109
+ 0,
110
+ );
111
+ expect(saved.auth).toEqual({ emailCompletionEnabled: false });
112
+ expect(saved.invite).toEqual({});
113
+ expect(saved.rateLimits).toEqual({ maxActiveRunTasksPerTenant: null });
114
+
115
+ const reloaded = await store.get();
116
+ expect(reloaded?.auth).toEqual({ emailCompletionEnabled: false });
117
+ expect(reloaded?.invite).toEqual({});
118
+ expect(reloaded?.rateLimits).toEqual({ maxActiveRunTasksPerTenant: null });
119
+ });
120
+ });
@@ -0,0 +1,104 @@
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 { ExternalIdentityConflictError } from "@axiom-lattice/protocols";
6
+ import { closeDatabase, initDatabase } from "../database";
7
+ import { LocalUserExternalIdentityStore } from "../stores/LocalUserExternalIdentityStore";
8
+
9
+ const nextDbPath = () =>
10
+ path.join(tmpdir(), `lt-identity-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
11
+
12
+ describe("LocalUserExternalIdentityStore", () => {
13
+ let dbPath: string;
14
+
15
+ afterEach(() => {
16
+ closeDatabase();
17
+ if (dbPath && existsSync(dbPath)) unlinkSync(dbPath);
18
+ });
19
+
20
+ it("links, reads, lists and unlinks", async () => {
21
+ dbPath = nextDbPath();
22
+ const store = new LocalUserExternalIdentityStore(await initDatabase({ dbPath }));
23
+
24
+ await store.link({
25
+ userId: "user-1",
26
+ providerId: "oidc",
27
+ issuer: "https://idp.example.com",
28
+ subject: "sub-1",
29
+ email: "user@example.com",
30
+ linkedAt: new Date("2026-01-01T00:00:00.000Z"),
31
+ });
32
+
33
+ const found = await store.getByProviderSubject(
34
+ "oidc",
35
+ "https://idp.example.com",
36
+ "sub-1",
37
+ );
38
+ expect(found).toMatchObject({
39
+ userId: "user-1",
40
+ providerId: "oidc",
41
+ issuer: "https://idp.example.com",
42
+ subject: "sub-1",
43
+ email: "user@example.com",
44
+ });
45
+ expect(found?.linkedAt).toBeInstanceOf(Date);
46
+
47
+ await store.link({
48
+ userId: "user-1",
49
+ providerId: "keycloak",
50
+ issuer: "https://keycloak.example.com",
51
+ subject: "sub-2",
52
+ linkedAt: new Date("2026-01-02T00:00:00.000Z"),
53
+ });
54
+ expect(await store.listByUser("user-1")).toHaveLength(2);
55
+
56
+ await store.unlink("oidc", "https://idp.example.com", "sub-1");
57
+ expect(
58
+ await store.getByProviderSubject("oidc", "https://idp.example.com", "sub-1"),
59
+ ).toBeNull();
60
+ expect(await store.listByUser("user-1")).toHaveLength(1);
61
+ });
62
+
63
+ it("isolates the same subject across issuers", async () => {
64
+ dbPath = nextDbPath();
65
+ const store = new LocalUserExternalIdentityStore(await initDatabase({ dbPath }));
66
+ await store.link({
67
+ userId: "user-a",
68
+ providerId: "oidc",
69
+ issuer: "https://idp-a.example.com",
70
+ subject: "sub-1",
71
+ linkedAt: new Date("2026-01-01T00:00:00.000Z"),
72
+ });
73
+ await store.link({
74
+ userId: "user-b",
75
+ providerId: "oidc",
76
+ issuer: "https://idp-b.example.com",
77
+ subject: "sub-1",
78
+ linkedAt: new Date("2026-01-01T00:00:00.000Z"),
79
+ });
80
+ expect(
81
+ await store.getByProviderSubject("oidc", "https://idp-a.example.com", "sub-1"),
82
+ ).toMatchObject({ userId: "user-a" });
83
+ expect(
84
+ await store.getByProviderSubject("oidc", "https://idp-b.example.com", "sub-1"),
85
+ ).toMatchObject({ userId: "user-b" });
86
+ });
87
+
88
+ it("is idempotent for the same user and rejects a different user", async () => {
89
+ dbPath = nextDbPath();
90
+ const store = new LocalUserExternalIdentityStore(await initDatabase({ dbPath }));
91
+ const base = {
92
+ providerId: "oidc",
93
+ issuer: "https://idp.example.com",
94
+ subject: "sub-1",
95
+ linkedAt: new Date("2026-01-01T00:00:00.000Z"),
96
+ };
97
+
98
+ await store.link({ ...base, userId: "user-1" });
99
+ await expect(store.link({ ...base, userId: "user-1" })).resolves.toBeUndefined();
100
+ await expect(store.link({ ...base, userId: "user-2" })).rejects.toBeInstanceOf(
101
+ ExternalIdentityConflictError,
102
+ );
103
+ });
104
+ });
@@ -0,0 +1,44 @@
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 } from "../database";
6
+ import { LocalUserStore } from "../stores/LocalUserStore";
7
+
8
+ const dbPath = path.join(tmpdir(), `lt-user-email-${Date.now()}.db`);
9
+
10
+ afterEach(() => {
11
+ closeDatabase();
12
+ if (existsSync(dbPath)) unlinkSync(dbPath);
13
+ });
14
+
15
+ describe("LocalUserStore email lookup", () => {
16
+ it("matches case-insensitively", async () => {
17
+ const store = new LocalUserStore(await initDatabase({ dbPath }));
18
+ await store.createUser("user-1", {
19
+ email: "User@Example.COM",
20
+ name: "User",
21
+ status: "active",
22
+ });
23
+ await expect(store.getUserByEmail("user@example.com")).resolves.toMatchObject({
24
+ id: "user-1",
25
+ });
26
+ });
27
+
28
+ it("rejects an email that differs only by case", async () => {
29
+ const store = new LocalUserStore(await initDatabase({ dbPath }));
30
+ await store.createUser("user-1", {
31
+ email: "User@Example.COM",
32
+ name: "User",
33
+ status: "active",
34
+ });
35
+
36
+ await expect(
37
+ store.createUser("user-2", {
38
+ email: "user@example.com",
39
+ name: "Other",
40
+ status: "active",
41
+ }),
42
+ ).rejects.toThrow();
43
+ });
44
+ });
@@ -29,6 +29,13 @@ import { LocalProjectRoomReadStateStore } from "./stores/LocalProjectRoomReadSta
29
29
  import { LocalUserStore } from "./stores/LocalUserStore";
30
30
  import { LocalTenantStore } from "./stores/LocalTenantStore";
31
31
  import { LocalUserTenantLinkStore } from "./stores/LocalUserTenantLinkStore";
32
+ import { LocalUserExternalIdentityStore } from "./stores/LocalUserExternalIdentityStore";
33
+ import { LocalOidcProviderConfigStore } from "./stores/LocalOidcProviderConfigStore";
34
+ import { LocalPlatformMemberStore } from "./stores/LocalPlatformMemberStore";
35
+ import { LocalPlatformInvitationStore } from "./stores/LocalPlatformInvitationStore";
36
+ import { LocalOidcIdentityClaimStore } from "./stores/LocalOidcIdentityClaimStore";
37
+ import { LocalInviteLinkStore } from "./stores/LocalInviteLinkStore";
38
+ import { LocalPlatformSettingsStore } from "./stores/LocalPlatformSettingsStore";
32
39
  import { LocalDatabaseConfigStore } from "./stores/LocalDatabaseConfigStore";
33
40
  import { LocalConnectionStore } from "./stores/LocalConnectionStore";
34
41
  import { LocalMetricsServerConfigStore } from "./stores/LocalMetricsServerConfigStore";
@@ -83,6 +90,13 @@ export async function createLocalStoreConfig(options: LocalStoreConfigOptions =
83
90
  user: new LocalUserStore(db),
84
91
  tenant: new LocalTenantStore(db),
85
92
  userTenantLink: new LocalUserTenantLinkStore(db),
93
+ userExternalIdentity: new LocalUserExternalIdentityStore(db),
94
+ oidcProviderConfig: new LocalOidcProviderConfigStore(db),
95
+ platformMember: new LocalPlatformMemberStore(db),
96
+ platformInvitation: new LocalPlatformInvitationStore(db),
97
+ oidcIdentityClaim: new LocalOidcIdentityClaimStore(db),
98
+ inviteLink: new LocalInviteLinkStore(db),
99
+ platformSettings: new LocalPlatformSettingsStore(db),
86
100
  database: new LocalDatabaseConfigStore(db),
87
101
  connection: new LocalConnectionStore(db),
88
102
  metrics: new LocalMetricsServerConfigStore(db),
package/src/index.ts CHANGED
@@ -40,6 +40,13 @@ export { LocalProjectRoomReadStateStore } from "./stores/LocalProjectRoomReadSta
40
40
  export { LocalUserStore } from "./stores/LocalUserStore";
41
41
  export { LocalTenantStore } from "./stores/LocalTenantStore";
42
42
  export { LocalUserTenantLinkStore } from "./stores/LocalUserTenantLinkStore";
43
+ export { LocalUserExternalIdentityStore } from "./stores/LocalUserExternalIdentityStore";
44
+ export { LocalOidcProviderConfigStore } from "./stores/LocalOidcProviderConfigStore";
45
+ export { LocalPlatformMemberStore } from "./stores/LocalPlatformMemberStore";
46
+ export { LocalPlatformInvitationStore } from "./stores/LocalPlatformInvitationStore";
47
+ export { LocalOidcIdentityClaimStore } from "./stores/LocalOidcIdentityClaimStore";
48
+ export { LocalInviteLinkStore } from "./stores/LocalInviteLinkStore";
49
+ export { LocalPlatformSettingsStore } from "./stores/LocalPlatformSettingsStore";
43
50
  export { LocalDatabaseConfigStore } from "./stores/LocalDatabaseConfigStore";
44
51
  export { LocalConnectionStore } from "./stores/LocalConnectionStore";
45
52
  export { LocalMetricsServerConfigStore } from "./stores/LocalMetricsServerConfigStore";
@@ -0,0 +1,162 @@
1
+ import { encrypt, safeDecrypt } from "@axiom-lattice/core";
2
+ import {
3
+ normalizeInviteLinkEmail,
4
+ type CreateInviteLinkInput,
5
+ type InviteLink,
6
+ type InviteLinkScope,
7
+ type InviteLinkStore,
8
+ } from "@axiom-lattice/protocols";
9
+ import type { PlatformRole, UserTenantRole } from "@axiom-lattice/protocols";
10
+ import { DatabaseWrapper, ensureTable, nowISO, parseISO } from "../database";
11
+
12
+ const DDL = `
13
+ CREATE TABLE IF NOT EXISTS lattice_invite_links (
14
+ id TEXT NOT NULL PRIMARY KEY,
15
+ scope TEXT NOT NULL,
16
+ token_hash TEXT NOT NULL UNIQUE,
17
+ token_encrypted TEXT NOT NULL,
18
+ email TEXT,
19
+ platform_role TEXT,
20
+ tenant_id TEXT,
21
+ tenant_role TEXT,
22
+ created_by TEXT,
23
+ created_at TEXT NOT NULL,
24
+ updated_at TEXT NOT NULL,
25
+ expires_at TEXT NOT NULL,
26
+ max_uses INTEGER NOT NULL,
27
+ used_count INTEGER NOT NULL,
28
+ revoked_at TEXT
29
+ );
30
+ CREATE UNIQUE INDEX IF NOT EXISTS lattice_invite_links_token_hash
31
+ ON lattice_invite_links (token_hash);
32
+ `;
33
+
34
+ interface LinkRow {
35
+ id: string;
36
+ scope: InviteLinkScope;
37
+ token_hash: string;
38
+ token_encrypted: string;
39
+ email: string | null;
40
+ platform_role: PlatformRole | null;
41
+ tenant_id: string | null;
42
+ tenant_role: UserTenantRole | null;
43
+ created_by: string | null;
44
+ created_at: string;
45
+ updated_at: string;
46
+ expires_at: string;
47
+ max_uses: number;
48
+ used_count: number;
49
+ revoked_at: string | null;
50
+ }
51
+
52
+ function mapRow(row: LinkRow): InviteLink {
53
+ return {
54
+ id: row.id,
55
+ scope: row.scope,
56
+ token: safeDecrypt(
57
+ row.token_encrypted,
58
+ `Invite link "${row.id}" token`,
59
+ ),
60
+ tokenHash: row.token_hash,
61
+ ...(row.email !== null ? { email: row.email } : {}),
62
+ ...(row.platform_role !== null ? { platformRole: row.platform_role } : {}),
63
+ ...(row.tenant_id !== null ? { tenantId: row.tenant_id } : {}),
64
+ ...(row.tenant_role !== null ? { tenantRole: row.tenant_role } : {}),
65
+ ...(row.created_by !== null ? { createdBy: row.created_by } : {}),
66
+ createdAt: parseISO(row.created_at),
67
+ updatedAt: parseISO(row.updated_at),
68
+ expiresAt: parseISO(row.expires_at),
69
+ maxUses: Number(row.max_uses),
70
+ usedCount: Number(row.used_count),
71
+ ...(row.revoked_at !== null ? { revokedAt: parseISO(row.revoked_at) } : {}),
72
+ };
73
+ }
74
+
75
+ /** SQLite implementation of {@link InviteLinkStore}. */
76
+ export class LocalInviteLinkStore implements InviteLinkStore {
77
+ private readonly db: DatabaseWrapper;
78
+
79
+ constructor(db: DatabaseWrapper) {
80
+ this.db = db;
81
+ ensureTable(db, DDL);
82
+ }
83
+
84
+ async list(): Promise<InviteLink[]> {
85
+ const rows = this.db
86
+ .prepare(
87
+ `SELECT * FROM lattice_invite_links
88
+ ORDER BY created_at DESC, id DESC`,
89
+ )
90
+ .all() as unknown as LinkRow[];
91
+ return rows.map(mapRow);
92
+ }
93
+
94
+ async get(id: string): Promise<InviteLink | null> {
95
+ const row = this.db
96
+ .prepare(`SELECT * FROM lattice_invite_links WHERE id = ?`)
97
+ .get(id) as unknown as LinkRow | undefined;
98
+ return row ? mapRow(row) : null;
99
+ }
100
+
101
+ async getByTokenHash(tokenHash: string): Promise<InviteLink | null> {
102
+ const row = this.db
103
+ .prepare(`SELECT * FROM lattice_invite_links WHERE token_hash = ?`)
104
+ .get(tokenHash) as unknown as LinkRow | undefined;
105
+ return row ? mapRow(row) : null;
106
+ }
107
+
108
+ async create(input: CreateInviteLinkInput): Promise<InviteLink> {
109
+ const now = nowISO();
110
+ this.db
111
+ .prepare(
112
+ `INSERT INTO lattice_invite_links
113
+ (id, scope, token_hash, token_encrypted, email, platform_role,
114
+ tenant_id, tenant_role, created_by, created_at, updated_at,
115
+ expires_at, max_uses, used_count, revoked_at)
116
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, NULL)`,
117
+ )
118
+ .run(
119
+ input.id,
120
+ input.scope,
121
+ input.tokenHash,
122
+ encrypt(input.token),
123
+ input.email ? normalizeInviteLinkEmail(input.email) : null,
124
+ input.platformRole ?? null,
125
+ input.tenantId ?? null,
126
+ input.tenantRole ?? null,
127
+ input.createdBy ?? null,
128
+ now,
129
+ now,
130
+ input.expiresAt.toISOString(),
131
+ input.maxUses,
132
+ );
133
+ const stored = await this.get(input.id);
134
+ if (!stored) throw new Error("Invite link was not persisted");
135
+ return stored;
136
+ }
137
+
138
+ async consume(tokenHash: string, now: Date): Promise<InviteLink | null> {
139
+ const result = this.db
140
+ .prepare(
141
+ `UPDATE lattice_invite_links
142
+ SET used_count = used_count + 1, updated_at = ?
143
+ WHERE token_hash = ?
144
+ AND revoked_at IS NULL
145
+ AND expires_at > ?
146
+ AND used_count < max_uses`,
147
+ )
148
+ .run(now.toISOString(), tokenHash, now.toISOString());
149
+ return result.changes > 0 ? this.getByTokenHash(tokenHash) : null;
150
+ }
151
+
152
+ async revoke(id: string, now: Date): Promise<InviteLink | null> {
153
+ const result = this.db
154
+ .prepare(
155
+ `UPDATE lattice_invite_links
156
+ SET revoked_at = ?, updated_at = ?
157
+ WHERE id = ? AND revoked_at IS NULL`,
158
+ )
159
+ .run(now.toISOString(), now.toISOString(), id);
160
+ return result.changes > 0 ? this.get(id) : this.get(id);
161
+ }
162
+ }