@tangle-network/agent-app 1.0.4 → 1.0.6

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.
@@ -54,23 +54,50 @@ function identifier(value, field) {
54
54
  if (!SQL_IDENTIFIER.test(value)) throw new Error(`createD1TangleIdentityStore: invalid ${field}`);
55
55
  return value;
56
56
  }
57
+ var DEFAULT_HOST_SCHEMA = {
58
+ user: {
59
+ table: "user",
60
+ columns: { id: "id", name: "name", email: "email", emailVerified: "emailVerified", createdAt: "createdAt", updatedAt: "updatedAt" }
61
+ },
62
+ session: {
63
+ table: "session",
64
+ columns: { id: "id", userId: "userId", token: "token", expiresAt: "expiresAt", ipAddress: "ipAddress", userAgent: "userAgent", createdAt: "createdAt", updatedAt: "updatedAt" }
65
+ },
66
+ account: {
67
+ table: "account",
68
+ columns: { id: "id", userId: "userId", accountId: "accountId", providerId: "providerId", createdAt: "createdAt", updatedAt: "updatedAt" }
69
+ }
70
+ };
71
+ function hostTable(value, field) {
72
+ return {
73
+ table: identifier(value.table, `${field}.table`),
74
+ columns: Object.fromEntries(Object.entries(value.columns).map(([column, physical]) => [column, identifier(physical, `${field}.columns.${column}`)]))
75
+ };
76
+ }
57
77
  function randomToken() {
58
78
  return Array.from(crypto.getRandomValues(new Uint8Array(32)), (byte) => byte.toString(16).padStart(2, "0")).join("");
59
79
  }
60
80
  function createD1TangleIdentityStore(options) {
61
81
  const { db, linkingUserId } = options;
62
82
  const provider = TANGLE_IDENTITY_PROVIDER_ID;
83
+ const host = options.hostSchema ?? DEFAULT_HOST_SCHEMA;
84
+ const userTable = hostTable(host.user, "hostSchema.user");
85
+ const sessionTable = hostTable(host.session, "hostSchema.session");
86
+ const accountTable = hostTable(host.account, "hostSchema.account");
87
+ const u = userTable.columns;
88
+ const s = sessionTable.columns;
89
+ const a = accountTable.columns;
63
90
  const legacy = options.legacyLinkTable && {
64
91
  table: identifier(options.legacyLinkTable.table, "legacyLinkTable.table"),
65
92
  userId: identifier(options.legacyLinkTable.userIdColumn, "legacyLinkTable.userIdColumn"),
66
93
  platformUserId: identifier(options.legacyLinkTable.platformUserIdColumn, "legacyLinkTable.platformUserIdColumn")
67
94
  };
68
- const selectAccount = `SELECT u.id AS userId, u.email AS email, u.emailVerified AS emailVerified,
69
- a.accountId AS accountPlatformUserId,
95
+ const selectAccount = `SELECT u.${u.id} AS userId, u.${u.email} AS email, u.${u.emailVerified} AS emailVerified,
96
+ a.${a.accountId} AS accountPlatformUserId,
70
97
  ${legacy ? `l.${legacy.platformUserId}` : "NULL"} AS legacyPlatformUserId
71
- FROM user u
72
- LEFT JOIN account a ON a.userId = u.id AND a.providerId = '${provider}'
73
- ${legacy ? `LEFT JOIN ${legacy.table} l ON l.${legacy.userId} = u.id` : ""}`;
98
+ FROM ${userTable.table} u
99
+ LEFT JOIN ${accountTable.table} a ON a.${a.userId} = u.${u.id} AND a.${a.providerId} = '${provider}'
100
+ ${legacy ? `LEFT JOIN ${legacy.table} l ON l.${legacy.userId} = u.${u.id}` : ""}`;
74
101
  function toCandidate(row) {
75
102
  const fromAccount = row.accountPlatformUserId?.trim() || null;
76
103
  const fromLegacy = row.legacyPlatformUserId?.trim() || null;
@@ -83,7 +110,7 @@ function createD1TangleIdentityStore(options) {
83
110
  };
84
111
  }
85
112
  async function candidates(email, platformUserId) {
86
- const where = legacy ? `WHERE lower(trim(u.email)) = ? OR a.accountId = ? OR l.${legacy.platformUserId} = ?` : "WHERE lower(trim(u.email)) = ? OR a.accountId = ?";
113
+ const where = legacy ? `WHERE lower(trim(u.${u.email})) = ? OR a.${a.accountId} = ? OR l.${legacy.platformUserId} = ?` : `WHERE lower(trim(u.${u.email})) = ? OR a.${a.accountId} = ?`;
87
114
  const values = legacy ? [email, platformUserId, platformUserId] : [email, platformUserId];
88
115
  const { results } = await db.prepare(`${selectAccount} ${where}`).bind(...values).all();
89
116
  const rows = results.map(toCandidate);
@@ -107,7 +134,7 @@ function createD1TangleIdentityStore(options) {
107
134
  emailMatches: found.emailMatches
108
135
  });
109
136
  }
110
- const ownRow = await db.prepare(`${selectAccount} WHERE u.id = ?`).bind(linkingUserId).first();
137
+ const ownRow = await db.prepare(`${selectAccount} WHERE u.${u.id} = ?`).bind(linkingUserId).first();
111
138
  if (!ownRow) return { kind: "reject", reason: "email-match-mismatch" };
112
139
  const own = toCandidate(ownRow);
113
140
  if (own.divergent) return { kind: "reject", reason: "platform-id-email-conflict" };
@@ -133,7 +160,7 @@ function createD1TangleIdentityStore(options) {
133
160
  if (resolution.kind !== "create") throw new TangleSsoUserCreateError("The selected account changed");
134
161
  const userId = crypto.randomUUID();
135
162
  try {
136
- await db.prepare(`INSERT INTO user (id, name, email, emailVerified, createdAt, updatedAt)
163
+ await db.prepare(`INSERT INTO ${userTable.table} (${u.id}, ${u.name}, ${u.email}, ${u.emailVerified}, ${u.createdAt}, ${u.updatedAt})
137
164
  VALUES (?, ?, ?, 1, unixepoch(), unixepoch())`).bind(userId, name || normalizedEmail, normalizedEmail).run();
138
165
  } catch {
139
166
  const after = await store.resolveAccount({ email: normalizedEmail, platformUserId });
@@ -145,27 +172,27 @@ function createD1TangleIdentityStore(options) {
145
172
  },
146
173
  async createSession({ userId, expiresAt, ipAddress, userAgent }) {
147
174
  const token = randomToken();
148
- await db.prepare(`INSERT INTO session (id, userId, token, expiresAt, ipAddress, userAgent, createdAt, updatedAt)
175
+ await db.prepare(`INSERT INTO ${sessionTable.table} (${s.id}, ${s.userId}, ${s.token}, ${s.expiresAt}, ${s.ipAddress}, ${s.userAgent}, ${s.createdAt}, ${s.updatedAt})
149
176
  VALUES (?, ?, ?, ?, ?, ?, unixepoch(), unixepoch())`).bind(crypto.randomUUID(), userId, token, Math.floor(expiresAt.getTime() / 1e3), ipAddress, userAgent).run();
150
177
  return { token };
151
178
  },
152
179
  async saveTangleLink({ userId, sessionToken, tangleUserId, email }) {
153
180
  const platformUserId = tangleUserId.trim();
154
181
  const normalizedEmail = normalizeTangleSsoEmail(email);
155
- const session = await db.prepare("SELECT userId FROM session WHERE token = ? AND expiresAt > unixepoch()").bind(sessionToken).first();
182
+ const session = await db.prepare(`SELECT ${s.userId} AS userId FROM ${sessionTable.table} WHERE ${s.token} = ? AND ${s.expiresAt} > unixepoch()`).bind(sessionToken).first();
156
183
  if (session?.userId !== userId) throw new TangleSsoAccountConflictError("email-platform-id-conflict");
157
184
  const current = await store.resolveAccount({ email: normalizedEmail, platformUserId });
158
185
  if (current.kind === "reject") throw new TangleSsoAccountConflictError(current.reason);
159
186
  if (current.kind !== "existing" || current.userId !== userId) {
160
187
  throw new TangleSsoAccountConflictError("platform-id-email-conflict");
161
188
  }
162
- const liveSession = "EXISTS (SELECT 1 FROM session WHERE token = ? AND userId = ? AND expiresAt > unixepoch())";
163
- const emailFree = "NOT EXISTS (SELECT 1 FROM user WHERE lower(trim(email)) = ? AND id <> ?)";
164
- const linked = `EXISTS (SELECT 1 FROM account WHERE providerId = '${provider}' AND userId = ? AND accountId = ?)`;
189
+ const liveSession = `EXISTS (SELECT 1 FROM ${sessionTable.table} WHERE ${s.token} = ? AND ${s.userId} = ? AND ${s.expiresAt} > unixepoch())`;
190
+ const emailFree = `NOT EXISTS (SELECT 1 FROM ${userTable.table} WHERE lower(trim(${u.email})) = ? AND ${u.id} <> ?)`;
191
+ const linked = `EXISTS (SELECT 1 FROM ${accountTable.table} WHERE ${a.providerId} = '${provider}' AND ${a.userId} = ? AND ${a.accountId} = ?)`;
165
192
  const statements = [
166
- db.prepare(`INSERT INTO account (id, userId, accountId, providerId, createdAt, updatedAt)
193
+ db.prepare(`INSERT INTO ${accountTable.table} (${a.id}, ${a.userId}, ${a.accountId}, ${a.providerId}, ${a.createdAt}, ${a.updatedAt})
167
194
  SELECT ?, ?, ?, '${provider}', unixepoch(), unixepoch()
168
- WHERE EXISTS (SELECT 1 FROM user WHERE id = ?) AND ${liveSession} AND ${emailFree}
195
+ WHERE EXISTS (SELECT 1 FROM ${userTable.table} WHERE ${u.id} = ?) AND ${liveSession} AND ${emailFree}
169
196
  ON CONFLICT DO NOTHING`).bind(crypto.randomUUID(), userId, platformUserId, userId, sessionToken, userId, normalizedEmail, userId)
170
197
  ];
171
198
  if (legacy) {
@@ -173,9 +200,9 @@ function createD1TangleIdentityStore(options) {
173
200
  SELECT ?, ? WHERE ${linked}
174
201
  ON CONFLICT DO NOTHING`).bind(userId, platformUserId, userId, platformUserId));
175
202
  }
176
- statements.push(db.prepare(`UPDATE user SET emailVerified = CASE WHEN lower(trim(email)) = ? THEN 1 ELSE emailVerified END,
177
- updatedAt = unixepoch()
178
- WHERE id = ? AND ${liveSession} AND ${linked} AND ${emailFree}`).bind(normalizedEmail, userId, sessionToken, userId, userId, platformUserId, normalizedEmail, userId));
203
+ statements.push(db.prepare(`UPDATE ${userTable.table} SET ${u.emailVerified} = CASE WHEN lower(trim(${u.email})) = ? THEN 1 ELSE ${u.emailVerified} END,
204
+ ${u.updatedAt} = unixepoch()
205
+ WHERE ${u.id} = ? AND ${liveSession} AND ${linked} AND ${emailFree}`).bind(normalizedEmail, userId, sessionToken, userId, userId, platformUserId, normalizedEmail, userId));
179
206
  const results = await db.batch(statements);
180
207
  if (results[results.length - 1]?.meta?.changes !== 1) {
181
208
  throw new TangleSsoAccountConflictError("email-platform-id-conflict");
@@ -184,7 +211,7 @@ function createD1TangleIdentityStore(options) {
184
211
  // `saveTangleLink` is one atomic batch, so a rejected call wrote nothing;
185
212
  // removing the unpublished session is the whole cleanup.
186
213
  async deleteSession({ sessionToken }) {
187
- await db.prepare("DELETE FROM session WHERE token = ?").bind(sessionToken).run();
214
+ await db.prepare(`DELETE FROM ${sessionTable.table} WHERE ${s.token} = ?`).bind(sessionToken).run();
188
215
  }
189
216
  };
190
217
  return store;