clivly 0.24.0-next.1 → 0.25.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.
Files changed (72) hide show
  1. package/README.md +34 -7
  2. package/{app-id-DcQ4u1c8.cjs → app-id-C2F25WhK.cjs} +1 -1
  3. package/{app-id-5cB6yioz.mjs → app-id-CMMadyIC.mjs} +1 -1
  4. package/auth-better-auth.cjs +51 -0
  5. package/auth-better-auth.d.cts +51 -1
  6. package/auth-better-auth.d.mts +51 -1
  7. package/auth-better-auth.mjs +51 -1
  8. package/auth-clerk.cjs +53 -0
  9. package/auth-clerk.d.cts +12 -1
  10. package/auth-clerk.d.mts +12 -1
  11. package/auth-clerk.mjs +53 -1
  12. package/auth-supabase.cjs +10 -0
  13. package/auth-supabase.d.cts +17 -1
  14. package/auth-supabase.d.mts +17 -1
  15. package/auth-supabase.mjs +10 -1
  16. package/auth-webhook-3if7gY6b.mjs +162 -0
  17. package/auth-webhook-BihEUc9C.cjs +197 -0
  18. package/auth-webhook-DKdaCZrW.d.cts +30 -0
  19. package/auth-webhook-DKdaCZrW.d.mts +30 -0
  20. package/auth-workos.cjs +43 -0
  21. package/auth-workos.d.cts +12 -1
  22. package/auth-workos.d.mts +12 -1
  23. package/auth-workos.mjs +43 -1
  24. package/drizzle.cjs +264 -17
  25. package/drizzle.d.cts +23 -3
  26. package/drizzle.d.mts +23 -3
  27. package/drizzle.mjs +265 -19
  28. package/{from-sql-CFgXkCe2.cjs → from-sql-Dw2ipynp.cjs} +7 -1
  29. package/{from-sql-S8dSvU-e.d.cts → from-sql-MyPE5elx.d.cts} +1 -1
  30. package/{from-sql-CpGP7K3J.d.mts → from-sql-YW6LfdVK.d.mts} +1 -1
  31. package/{from-sql-BD7gR4bC.mjs → from-sql-kqs9CbQ-.mjs} +7 -1
  32. package/{index-CIupXz_w.d.cts → index-B4kWWHYm.d.cts} +2 -2
  33. package/{index-BoemTWH4.d.mts → index-CKElWhvq.d.mts} +2 -2
  34. package/index.cjs +3354 -2829
  35. package/index.d.cts +3 -3
  36. package/index.d.mts +3 -3
  37. package/index.mjs +3354 -2829
  38. package/{introspector-5w2x89RD.mjs → introspector-B1S7qmvy.mjs} +4 -4
  39. package/{introspector-DT_Ma59k.cjs → introspector-DRmEXDai.cjs} +4 -4
  40. package/kysely.cjs +163 -2
  41. package/kysely.d.cts +16 -3
  42. package/kysely.d.mts +16 -3
  43. package/kysely.mjs +163 -3
  44. package/{namespace-probe-CUR2zG2l.d.mts → namespace-probe-LKC4OU5X.d.mts} +54 -19
  45. package/package.json +1 -1
  46. package/{projection-guard-DOt_nbGn.mjs → projection-guard-CADdAdzg.mjs} +1 -1
  47. package/{projection-guard-C70l5U24.cjs → projection-guard-yhVTvx37.cjs} +1 -1
  48. package/sdk.cjs +1 -1
  49. package/sdk.d.cts +1 -1
  50. package/sdk.d.mts +1 -1
  51. package/sdk.mjs +1 -1
  52. package/sql.cjs +5 -5
  53. package/sql.d.cts +2 -2
  54. package/sql.d.mts +2 -2
  55. package/sql.mjs +5 -5
  56. package/{src-CZIdwwI2.cjs → src-BQasv4EL.cjs} +368 -38
  57. package/{src-tFhC1Ru2.mjs → src-CAn-zrEl.mjs} +368 -38
  58. package/{supabase-contact-BXQ0nnLq.cjs → supabase-contact-0GmBVpiQ.cjs} +24 -15
  59. package/{supabase-contact-3ke1KKUs.mjs → supabase-contact-D-oDC4Qk.mjs} +24 -15
  60. package/supabase.cjs +39 -9
  61. package/supabase.d.cts +3 -2
  62. package/supabase.d.mts +3 -2
  63. package/supabase.mjs +39 -9
  64. package/{sync-Q0O-2kFI.mjs → sync-CnWT5juF.mjs} +65 -5
  65. package/{sync-CdA9dgZz.cjs → sync-R0iVlooB.cjs} +94 -4
  66. package/track-writes-4yyZbTZX.d.cts +17 -0
  67. package/track-writes-BJSWg8wg.d.mts +17 -0
  68. package/track-writes-BnZAig2Y.mjs +77 -0
  69. package/track-writes-C22_e_W-.cjs +112 -0
  70. package/{types-CzL7lUH9.d.cts → types-BPG4l-oM.d.cts} +53 -18
  71. package/vite.d.cts +1 -1
  72. package/vite.d.mts +1 -1
@@ -0,0 +1,162 @@
1
+ // ../core/src/auth-webhook.ts
2
+ const MAX_BODY_BYTES = 524288;
3
+ /** How long the app gets to write its own row before the provider is asked to retry. */
4
+ const ROW_WAIT_MS = 2e3;
5
+ /**
6
+ * An event older than this is not retried. A row that never appears (a user
7
+ * the source filters out) would otherwise wake the database for days.
8
+ */
9
+ const RETRY_WINDOW_MS = 6e5;
10
+ const OK = 200;
11
+ const BAD_REQUEST = 400;
12
+ const UNAUTHORIZED = 401;
13
+ const METHOD_NOT_ALLOWED = 405;
14
+ const TOO_LARGE = 413;
15
+ const UNAVAILABLE = 503;
16
+ /** Signed timestamps further away than this are refused, so none can be replayed later. */
17
+ const SIGNATURE_TOLERANCE_MS = 3e5;
18
+ const reply = (status) => new Response(null, { status });
19
+ /** A request body as text, or null when it is larger than `maxBytes`. */
20
+ async function readLimitedText(request, maxBytes) {
21
+ if (Number(request.headers.get("content-length") ?? 0) > maxBytes) return null;
22
+ const reader = request.body?.getReader();
23
+ if (!reader) return "";
24
+ const decoder = new TextDecoder();
25
+ let text = "";
26
+ let size = 0;
27
+ for (;;) {
28
+ const { done, value } = await reader.read();
29
+ if (done) return text + decoder.decode();
30
+ size += value.byteLength;
31
+ if (size > maxBytes) {
32
+ await reader.cancel();
33
+ return null;
34
+ }
35
+ text += decoder.decode(value, { stream: true });
36
+ }
37
+ }
38
+ async function hmacSha256(secret, text) {
39
+ const key = await crypto.subtle.importKey("raw", new Uint8Array(secret), {
40
+ hash: "SHA-256",
41
+ name: "HMAC"
42
+ }, false, ["sign"]);
43
+ return new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(text)));
44
+ }
45
+ /** Equal and not empty, taking the same time wherever they differ. */
46
+ function sameBytes(a, b) {
47
+ if (a.length !== b.length || a.length === 0) return false;
48
+ let different = 0;
49
+ for (const [index, byte] of a.entries()) different |= byte ^ (b[index] ?? 0);
50
+ return different === 0;
51
+ }
52
+ const timeOf = (value) => typeof value === "number" ? value : Date.parse(value);
53
+ /** A provider's event time (ms or ISO text) as ms, or null. */
54
+ function eventTime(value) {
55
+ if (typeof value !== "number" && typeof value !== "string") return null;
56
+ const time = timeOf(value);
57
+ return Number.isFinite(time) ? time : null;
58
+ }
59
+ function createUserPush(options) {
60
+ const { clivly, resolveId } = options;
61
+ const entity = options.entity ?? "contacts";
62
+ const sleep = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
63
+ const attempt = async (userId) => {
64
+ const id = resolveId ? await resolveId(userId) : userId;
65
+ if (id === null) return {
66
+ id,
67
+ missing: true,
68
+ retry: false
69
+ };
70
+ const { missing, retry } = await clivly.pushById(entity, [id]);
71
+ return {
72
+ id,
73
+ missing: missing.length > 0,
74
+ retry
75
+ };
76
+ };
77
+ const push = async ({ deleted, id }) => {
78
+ let result = await attempt(id);
79
+ if (!result.retry && result.missing !== deleted) {
80
+ await sleep(ROW_WAIT_MS);
81
+ result = await attempt(id);
82
+ }
83
+ if (result.retry) return true;
84
+ if (!deleted) return result.missing;
85
+ if (result.missing && result.id !== null) await clivly.pushDelete(entity, [result.id]);
86
+ return false;
87
+ };
88
+ return async (event) => {
89
+ try {
90
+ return await push(event);
91
+ } catch (error) {
92
+ console.warn("Clivly instant push: the user could not be pushed.", error);
93
+ return true;
94
+ }
95
+ };
96
+ }
97
+ /** A webhook endpoint that keeps one user's row in Clivly current. */
98
+ function createUserPushHandler(options) {
99
+ const { parse, verify } = options;
100
+ const now = options.now ?? Date.now;
101
+ const push = createUserPush(options);
102
+ return async (request) => {
103
+ if (request.method !== "POST") return reply(METHOD_NOT_ALLOWED);
104
+ const body = await readLimitedText(request, MAX_BODY_BYTES);
105
+ if (body === null) return reply(TOO_LARGE);
106
+ if (!await verify(request.headers, body, now()).catch(() => false)) return reply(UNAUTHORIZED);
107
+ let event;
108
+ try {
109
+ event = parse(JSON.parse(body));
110
+ } catch {
111
+ return reply(BAD_REQUEST);
112
+ }
113
+ if (!event) return reply(OK);
114
+ const again = await push(event);
115
+ const recent = event.at !== null && now() - event.at < RETRY_WINDOW_MS;
116
+ return reply(again && recent ? UNAVAILABLE : OK);
117
+ };
118
+ }
119
+ const TOKEN_SHAPE = /^[0-9a-f]{64}$/;
120
+ const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
121
+ const MAX_TOKEN_BODY_BYTES = 1024;
122
+ const ACCEPTED = 202;
123
+ const tokenEvent = (body) => {
124
+ try {
125
+ const { deleted, id } = JSON.parse(body);
126
+ return typeof id === "string" && UUID.test(id) ? {
127
+ at: null,
128
+ deleted: deleted === true,
129
+ id
130
+ } : null;
131
+ } catch {
132
+ return null;
133
+ }
134
+ };
135
+ /**
136
+ * An endpoint for a trigger inside the host's own database, which proves
137
+ * itself with a token and sends only a user id. Nothing in the body is ever
138
+ * stored: the row is read again. The trigger does not retry, so this answers
139
+ * 202 whatever becomes of the push.
140
+ */
141
+ function createTokenPushHandler(options) {
142
+ const { token, waitUntil } = options;
143
+ const push = createUserPush(options);
144
+ const isTrigger = async (presented) => {
145
+ if (!TOKEN_SHAPE.test(presented)) return false;
146
+ const encoder = new TextEncoder();
147
+ const expected = typeof token === "function" ? await (async () => await token(presented))().catch(() => null) : token;
148
+ return sameBytes(encoder.encode(expected ?? ""), encoder.encode(presented));
149
+ };
150
+ return async (request) => {
151
+ if (request.method !== "POST") return reply(METHOD_NOT_ALLOWED);
152
+ if (!await isTrigger(request.headers.get("x-clivly-push-token") ?? "")) return reply(UNAUTHORIZED);
153
+ const body = await readLimitedText(request, MAX_TOKEN_BODY_BYTES);
154
+ const event = body === null ? null : tokenEvent(body);
155
+ if (!event) return reply(BAD_REQUEST);
156
+ const work = push(event);
157
+ if (waitUntil) waitUntil(work);
158
+ else await work;
159
+ return reply(ACCEPTED);
160
+ };
161
+ }
162
+ export { hmacSha256 as a, eventTime as i, createTokenPushHandler as n, sameBytes as o, createUserPushHandler as r, SIGNATURE_TOLERANCE_MS as t };
@@ -0,0 +1,197 @@
1
+ // ../core/src/auth-webhook.ts
2
+ const MAX_BODY_BYTES = 524288;
3
+ /** How long the app gets to write its own row before the provider is asked to retry. */
4
+ const ROW_WAIT_MS = 2e3;
5
+ /**
6
+ * An event older than this is not retried. A row that never appears (a user
7
+ * the source filters out) would otherwise wake the database for days.
8
+ */
9
+ const RETRY_WINDOW_MS = 6e5;
10
+ const OK = 200;
11
+ const BAD_REQUEST = 400;
12
+ const UNAUTHORIZED = 401;
13
+ const METHOD_NOT_ALLOWED = 405;
14
+ const TOO_LARGE = 413;
15
+ const UNAVAILABLE = 503;
16
+ /** Signed timestamps further away than this are refused, so none can be replayed later. */
17
+ const SIGNATURE_TOLERANCE_MS = 3e5;
18
+ const reply = (status) => new Response(null, { status });
19
+ /** A request body as text, or null when it is larger than `maxBytes`. */
20
+ async function readLimitedText(request, maxBytes) {
21
+ if (Number(request.headers.get("content-length") ?? 0) > maxBytes) return null;
22
+ const reader = request.body?.getReader();
23
+ if (!reader) return "";
24
+ const decoder = new TextDecoder();
25
+ let text = "";
26
+ let size = 0;
27
+ for (;;) {
28
+ const { done, value } = await reader.read();
29
+ if (done) return text + decoder.decode();
30
+ size += value.byteLength;
31
+ if (size > maxBytes) {
32
+ await reader.cancel();
33
+ return null;
34
+ }
35
+ text += decoder.decode(value, { stream: true });
36
+ }
37
+ }
38
+ async function hmacSha256(secret, text) {
39
+ const key = await crypto.subtle.importKey("raw", new Uint8Array(secret), {
40
+ hash: "SHA-256",
41
+ name: "HMAC"
42
+ }, false, ["sign"]);
43
+ return new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(text)));
44
+ }
45
+ /** Equal and not empty, taking the same time wherever they differ. */
46
+ function sameBytes(a, b) {
47
+ if (a.length !== b.length || a.length === 0) return false;
48
+ let different = 0;
49
+ for (const [index, byte] of a.entries()) different |= byte ^ (b[index] ?? 0);
50
+ return different === 0;
51
+ }
52
+ const timeOf = (value) => typeof value === "number" ? value : Date.parse(value);
53
+ /** A provider's event time (ms or ISO text) as ms, or null. */
54
+ function eventTime(value) {
55
+ if (typeof value !== "number" && typeof value !== "string") return null;
56
+ const time = timeOf(value);
57
+ return Number.isFinite(time) ? time : null;
58
+ }
59
+ function createUserPush(options) {
60
+ const { clivly, resolveId } = options;
61
+ const entity = options.entity ?? "contacts";
62
+ const sleep = options.sleep ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
63
+ const attempt = async (userId) => {
64
+ const id = resolveId ? await resolveId(userId) : userId;
65
+ if (id === null) return {
66
+ id,
67
+ missing: true,
68
+ retry: false
69
+ };
70
+ const { missing, retry } = await clivly.pushById(entity, [id]);
71
+ return {
72
+ id,
73
+ missing: missing.length > 0,
74
+ retry
75
+ };
76
+ };
77
+ const push = async ({ deleted, id }) => {
78
+ let result = await attempt(id);
79
+ if (!result.retry && result.missing !== deleted) {
80
+ await sleep(ROW_WAIT_MS);
81
+ result = await attempt(id);
82
+ }
83
+ if (result.retry) return true;
84
+ if (!deleted) return result.missing;
85
+ if (result.missing && result.id !== null) await clivly.pushDelete(entity, [result.id]);
86
+ return false;
87
+ };
88
+ return async (event) => {
89
+ try {
90
+ return await push(event);
91
+ } catch (error) {
92
+ console.warn("Clivly instant push: the user could not be pushed.", error);
93
+ return true;
94
+ }
95
+ };
96
+ }
97
+ /** A webhook endpoint that keeps one user's row in Clivly current. */
98
+ function createUserPushHandler(options) {
99
+ const { parse, verify } = options;
100
+ const now = options.now ?? Date.now;
101
+ const push = createUserPush(options);
102
+ return async (request) => {
103
+ if (request.method !== "POST") return reply(METHOD_NOT_ALLOWED);
104
+ const body = await readLimitedText(request, MAX_BODY_BYTES);
105
+ if (body === null) return reply(TOO_LARGE);
106
+ if (!await verify(request.headers, body, now()).catch(() => false)) return reply(UNAUTHORIZED);
107
+ let event;
108
+ try {
109
+ event = parse(JSON.parse(body));
110
+ } catch {
111
+ return reply(BAD_REQUEST);
112
+ }
113
+ if (!event) return reply(OK);
114
+ const again = await push(event);
115
+ const recent = event.at !== null && now() - event.at < RETRY_WINDOW_MS;
116
+ return reply(again && recent ? UNAVAILABLE : OK);
117
+ };
118
+ }
119
+ const TOKEN_SHAPE = /^[0-9a-f]{64}$/;
120
+ const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
121
+ const MAX_TOKEN_BODY_BYTES = 1024;
122
+ const ACCEPTED = 202;
123
+ const tokenEvent = (body) => {
124
+ try {
125
+ const { deleted, id } = JSON.parse(body);
126
+ return typeof id === "string" && UUID.test(id) ? {
127
+ at: null,
128
+ deleted: deleted === true,
129
+ id
130
+ } : null;
131
+ } catch {
132
+ return null;
133
+ }
134
+ };
135
+ /**
136
+ * An endpoint for a trigger inside the host's own database, which proves
137
+ * itself with a token and sends only a user id. Nothing in the body is ever
138
+ * stored: the row is read again. The trigger does not retry, so this answers
139
+ * 202 whatever becomes of the push.
140
+ */
141
+ function createTokenPushHandler(options) {
142
+ const { token, waitUntil } = options;
143
+ const push = createUserPush(options);
144
+ const isTrigger = async (presented) => {
145
+ if (!TOKEN_SHAPE.test(presented)) return false;
146
+ const encoder = new TextEncoder();
147
+ const expected = typeof token === "function" ? await (async () => await token(presented))().catch(() => null) : token;
148
+ return sameBytes(encoder.encode(expected ?? ""), encoder.encode(presented));
149
+ };
150
+ return async (request) => {
151
+ if (request.method !== "POST") return reply(METHOD_NOT_ALLOWED);
152
+ if (!await isTrigger(request.headers.get("x-clivly-push-token") ?? "")) return reply(UNAUTHORIZED);
153
+ const body = await readLimitedText(request, MAX_TOKEN_BODY_BYTES);
154
+ const event = body === null ? null : tokenEvent(body);
155
+ if (!event) return reply(BAD_REQUEST);
156
+ const work = push(event);
157
+ if (waitUntil) waitUntil(work);
158
+ else await work;
159
+ return reply(ACCEPTED);
160
+ };
161
+ }
162
+ Object.defineProperty(exports, "SIGNATURE_TOLERANCE_MS", {
163
+ enumerable: true,
164
+ get: function() {
165
+ return SIGNATURE_TOLERANCE_MS;
166
+ }
167
+ });
168
+ Object.defineProperty(exports, "createTokenPushHandler", {
169
+ enumerable: true,
170
+ get: function() {
171
+ return createTokenPushHandler;
172
+ }
173
+ });
174
+ Object.defineProperty(exports, "createUserPushHandler", {
175
+ enumerable: true,
176
+ get: function() {
177
+ return createUserPushHandler;
178
+ }
179
+ });
180
+ Object.defineProperty(exports, "eventTime", {
181
+ enumerable: true,
182
+ get: function() {
183
+ return eventTime;
184
+ }
185
+ });
186
+ Object.defineProperty(exports, "hmacSha256", {
187
+ enumerable: true,
188
+ get: function() {
189
+ return hmacSha256;
190
+ }
191
+ });
192
+ Object.defineProperty(exports, "sameBytes", {
193
+ enumerable: true,
194
+ get: function() {
195
+ return sameBytes;
196
+ }
197
+ });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Instant push from an auth provider's webhook: the part every provider
3
+ * shares. The webhook goes to the host's own app, which re-reads the user's
4
+ * row and pushes it, so no provider secret reaches Clivly. Web APIs only, so it
5
+ * runs on Node, Workers, Deno and edge runtimes.
6
+ */
7
+ /** What became of an instant push. */
8
+ interface InstantPushOutcome {
9
+ /** Ids the source did not return. */
10
+ missing: (string | number)[];
11
+ /** The push did not arrive and is worth trying again. */
12
+ retry: boolean;
13
+ }
14
+ /** The two calls a webhook needs from the Clivly SDK. */
15
+ interface UserPushSDK {
16
+ pushById(entity: string, ids: readonly (string | number)[]): Promise<InstantPushOutcome>;
17
+ pushDelete(entity: string, ids: readonly (string | number)[]): Promise<unknown>;
18
+ }
19
+ interface UserPushOptions {
20
+ /** Your Clivly SDK (the object returned by `createClivlySDK({...})`). */
21
+ clivly: UserPushSDK;
22
+ /** The entity key in your Clivly config that maps users. Default `"contacts"`. */
23
+ entity?: string;
24
+ /**
25
+ * Your row's id for the provider's user id, when they differ. Return null
26
+ * while there is no such row.
27
+ */
28
+ resolveId?: (userId: string) => Promise<string | number | null> | string | number | null;
29
+ }
30
+ export { UserPushOptions as n, UserPushSDK as r, InstantPushOutcome as t };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Instant push from an auth provider's webhook: the part every provider
3
+ * shares. The webhook goes to the host's own app, which re-reads the user's
4
+ * row and pushes it, so no provider secret reaches Clivly. Web APIs only, so it
5
+ * runs on Node, Workers, Deno and edge runtimes.
6
+ */
7
+ /** What became of an instant push. */
8
+ interface InstantPushOutcome {
9
+ /** Ids the source did not return. */
10
+ missing: (string | number)[];
11
+ /** The push did not arrive and is worth trying again. */
12
+ retry: boolean;
13
+ }
14
+ /** The two calls a webhook needs from the Clivly SDK. */
15
+ interface UserPushSDK {
16
+ pushById(entity: string, ids: readonly (string | number)[]): Promise<InstantPushOutcome>;
17
+ pushDelete(entity: string, ids: readonly (string | number)[]): Promise<unknown>;
18
+ }
19
+ interface UserPushOptions {
20
+ /** Your Clivly SDK (the object returned by `createClivlySDK({...})`). */
21
+ clivly: UserPushSDK;
22
+ /** The entity key in your Clivly config that maps users. Default `"contacts"`. */
23
+ entity?: string;
24
+ /**
25
+ * Your row's id for the provider's user id, when they differ. Return null
26
+ * while there is no such row.
27
+ */
28
+ resolveId?: (userId: string) => Promise<string | number | null> | string | number | null;
29
+ }
30
+ export { UserPushOptions as n, UserPushSDK as r, InstantPushOutcome as t };
package/auth-workos.cjs CHANGED
@@ -1,4 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_auth_webhook = require("./auth-webhook-BihEUc9C.cjs");
2
3
  let _workos_inc_node = require("@workos-inc/node");
3
4
  // ../auth-workos/src/map.ts
4
5
  function workosUserToClivlyUser(user) {
@@ -20,6 +21,47 @@ function readCookie(req, name) {
20
21
  }
21
22
  return null;
22
23
  }
24
+ // ../auth-workos/src/instant-push.ts
25
+ const USER_EVENTS = /* @__PURE__ */ new Set([
26
+ "user.created",
27
+ "user.updated",
28
+ "user.deleted"
29
+ ]);
30
+ const SIGNATURE_HEADER = /^t=(\d+),\s*v1=([0-9a-f]{64})$/i;
31
+ const HEX_PAIR = /../g;
32
+ const HEX = 16;
33
+ const fromHex = (text) => Uint8Array.from(text.match(HEX_PAIR) ?? [], (pair) => Number.parseInt(pair, HEX));
34
+ const verifyWorkOS = async (secret, headers, body, now) => {
35
+ const header = SIGNATURE_HEADER.exec(headers.get("workos-signature") ?? "");
36
+ const timestamp = header?.[1];
37
+ const signature = header?.[2];
38
+ if (!(secret && timestamp && signature)) return false;
39
+ if (!(Math.abs(now - Number(timestamp)) <= 3e5)) return false;
40
+ const expected = await require_auth_webhook.hmacSha256(new TextEncoder().encode(secret), `${timestamp}.${body}`);
41
+ return require_auth_webhook.sameBytes(fromHex(signature), expected);
42
+ };
43
+ const parse = (payload) => {
44
+ const event = payload;
45
+ const id = event?.data?.id;
46
+ if (!(typeof event?.event === "string" && USER_EVENTS.has(event.event)) || typeof id !== "string") return null;
47
+ return {
48
+ at: require_auth_webhook.eventTime(event.created_at),
49
+ deleted: event.event === "user.deleted",
50
+ id
51
+ };
52
+ };
53
+ /**
54
+ * A WorkOS webhook endpoint that pushes a user to Clivly the moment they sign
55
+ * up, change or are deleted. Subscribe it to `user.created`, `user.updated`
56
+ * and `user.deleted`.
57
+ */
58
+ function createWorkOSPushHandler({ signingSecret, ...options }) {
59
+ return require_auth_webhook.createUserPushHandler({
60
+ ...options,
61
+ parse,
62
+ verify: (headers, body, now) => verifyWorkOS(signingSecret, headers, body, now)
63
+ });
64
+ }
23
65
  // ../auth-workos/src/index.ts
24
66
  const DEFAULT_COOKIE_NAME = "wos-session";
25
67
  /**
@@ -42,4 +84,5 @@ function createWorkOSAuthAdapter(options) {
42
84
  } };
43
85
  }
44
86
  exports.createWorkOSAuthAdapter = createWorkOSAuthAdapter;
87
+ exports.createWorkOSPushHandler = createWorkOSPushHandler;
45
88
  exports.workosUserToClivlyUser = workosUserToClivlyUser;
package/auth-workos.d.cts CHANGED
@@ -1,4 +1,15 @@
1
1
  import { n as ClivlyUser, t as ClivlyAuthAdapter } from "./auth-adapter-C17dzlzF.cjs";
2
+ import { n as UserPushOptions, r as UserPushSDK, t as InstantPushOutcome } from "./auth-webhook-DKdaCZrW.cjs";
3
+ interface WorkOSPushOptions extends UserPushOptions {
4
+ /** The endpoint's signing secret from the WorkOS dashboard. */
5
+ signingSecret: string | undefined;
6
+ }
7
+ /**
8
+ * A WorkOS webhook endpoint that pushes a user to Clivly the moment they sign
9
+ * up, change or are deleted. Subscribe it to `user.created`, `user.updated`
10
+ * and `user.deleted`.
11
+ */
12
+ export declare function createWorkOSPushHandler({ signingSecret, ...options }: WorkOSPushOptions): (request: Request) => Promise<Response>;
2
13
  interface WorkOSLikeUser {
3
14
  email: string;
4
15
  firstName?: string | null;
@@ -22,4 +33,4 @@ export interface WorkOSAuthAdapterOptions {
22
33
  * CRM authorization lives in the separate `crm_members` layer.
23
34
  */
24
35
  export declare function createWorkOSAuthAdapter(options: WorkOSAuthAdapterOptions): ClivlyAuthAdapter;
25
- export type { WorkOSLikeUser };
36
+ export type { InstantPushOutcome, UserPushSDK, WorkOSLikeUser, WorkOSPushOptions };
package/auth-workos.d.mts CHANGED
@@ -1,4 +1,15 @@
1
1
  import { n as ClivlyUser, t as ClivlyAuthAdapter } from "./auth-adapter-CizFv7oU.mjs";
2
+ import { n as UserPushOptions, r as UserPushSDK, t as InstantPushOutcome } from "./auth-webhook-DKdaCZrW.mjs";
3
+ interface WorkOSPushOptions extends UserPushOptions {
4
+ /** The endpoint's signing secret from the WorkOS dashboard. */
5
+ signingSecret: string | undefined;
6
+ }
7
+ /**
8
+ * A WorkOS webhook endpoint that pushes a user to Clivly the moment they sign
9
+ * up, change or are deleted. Subscribe it to `user.created`, `user.updated`
10
+ * and `user.deleted`.
11
+ */
12
+ export declare function createWorkOSPushHandler({ signingSecret, ...options }: WorkOSPushOptions): (request: Request) => Promise<Response>;
2
13
  interface WorkOSLikeUser {
3
14
  email: string;
4
15
  firstName?: string | null;
@@ -22,4 +33,4 @@ export interface WorkOSAuthAdapterOptions {
22
33
  * CRM authorization lives in the separate `crm_members` layer.
23
34
  */
24
35
  export declare function createWorkOSAuthAdapter(options: WorkOSAuthAdapterOptions): ClivlyAuthAdapter;
25
- export type { WorkOSLikeUser };
36
+ export type { InstantPushOutcome, UserPushSDK, WorkOSLikeUser, WorkOSPushOptions };
package/auth-workos.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { a as hmacSha256, i as eventTime, o as sameBytes, r as createUserPushHandler } from "./auth-webhook-3if7gY6b.mjs";
1
2
  import { WorkOS } from "@workos-inc/node";
2
3
  // ../auth-workos/src/map.ts
3
4
  function workosUserToClivlyUser(user) {
@@ -19,6 +20,47 @@ function readCookie(req, name) {
19
20
  }
20
21
  return null;
21
22
  }
23
+ // ../auth-workos/src/instant-push.ts
24
+ const USER_EVENTS = /* @__PURE__ */ new Set([
25
+ "user.created",
26
+ "user.updated",
27
+ "user.deleted"
28
+ ]);
29
+ const SIGNATURE_HEADER = /^t=(\d+),\s*v1=([0-9a-f]{64})$/i;
30
+ const HEX_PAIR = /../g;
31
+ const HEX = 16;
32
+ const fromHex = (text) => Uint8Array.from(text.match(HEX_PAIR) ?? [], (pair) => Number.parseInt(pair, HEX));
33
+ const verifyWorkOS = async (secret, headers, body, now) => {
34
+ const header = SIGNATURE_HEADER.exec(headers.get("workos-signature") ?? "");
35
+ const timestamp = header?.[1];
36
+ const signature = header?.[2];
37
+ if (!(secret && timestamp && signature)) return false;
38
+ if (!(Math.abs(now - Number(timestamp)) <= 3e5)) return false;
39
+ const expected = await hmacSha256(new TextEncoder().encode(secret), `${timestamp}.${body}`);
40
+ return sameBytes(fromHex(signature), expected);
41
+ };
42
+ const parse = (payload) => {
43
+ const event = payload;
44
+ const id = event?.data?.id;
45
+ if (!(typeof event?.event === "string" && USER_EVENTS.has(event.event)) || typeof id !== "string") return null;
46
+ return {
47
+ at: eventTime(event.created_at),
48
+ deleted: event.event === "user.deleted",
49
+ id
50
+ };
51
+ };
52
+ /**
53
+ * A WorkOS webhook endpoint that pushes a user to Clivly the moment they sign
54
+ * up, change or are deleted. Subscribe it to `user.created`, `user.updated`
55
+ * and `user.deleted`.
56
+ */
57
+ function createWorkOSPushHandler({ signingSecret, ...options }) {
58
+ return createUserPushHandler({
59
+ ...options,
60
+ parse,
61
+ verify: (headers, body, now) => verifyWorkOS(signingSecret, headers, body, now)
62
+ });
63
+ }
22
64
  // ../auth-workos/src/index.ts
23
65
  const DEFAULT_COOKIE_NAME = "wos-session";
24
66
  /**
@@ -40,4 +82,4 @@ function createWorkOSAuthAdapter(options) {
40
82
  return workosUserToClivlyUser(result.user);
41
83
  } };
42
84
  }
43
- export { createWorkOSAuthAdapter, workosUserToClivlyUser };
85
+ export { createWorkOSAuthAdapter, createWorkOSPushHandler, workosUserToClivlyUser };