easy-ping 0.3.0 → 0.4.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/README.md +15 -4
- package/dist/adapters/drizzle.cjs +3 -2
- package/dist/adapters/drizzle.cjs.map +1 -1
- package/dist/adapters/drizzle.d.cts +34 -0
- package/dist/adapters/drizzle.d.ts +34 -0
- package/dist/adapters/drizzle.js +4 -3
- package/dist/adapters/drizzle.js.map +1 -1
- package/dist/adapters/mongodb.cjs +6 -2
- package/dist/adapters/mongodb.cjs.map +1 -1
- package/dist/adapters/mongodb.d.cts +1 -1
- package/dist/adapters/mongodb.d.ts +1 -1
- package/dist/adapters/mongodb.js +5 -2
- package/dist/adapters/mongodb.js.map +1 -1
- package/dist/adapters/postgres.cjs +3 -2
- package/dist/adapters/postgres.cjs.map +1 -1
- package/dist/adapters/postgres.d.cts +1 -1
- package/dist/adapters/postgres.d.ts +1 -1
- package/dist/adapters/postgres.js +3 -3
- package/dist/{chunk-OZSOIX23.js → chunk-3Y2MBUAW.js} +53 -12
- package/dist/chunk-3Y2MBUAW.js.map +1 -0
- package/dist/chunk-CYKAM7LE.js +226 -0
- package/dist/chunk-CYKAM7LE.js.map +1 -0
- package/dist/chunk-DG3ZL5NP.js +315 -0
- package/dist/chunk-DG3ZL5NP.js.map +1 -0
- package/dist/{chunk-NYDVNMKG.js → chunk-PSJHXZPR.js} +4 -3
- package/dist/chunk-PSJHXZPR.js.map +1 -0
- package/dist/{chunk-BV3U542P.js → chunk-W6I3B2CI.js} +2 -2
- package/dist/chunk-W6I3B2CI.js.map +1 -0
- package/dist/{chunk-RBDW4S6F.js → chunk-YEMRRMJQ.js} +3 -3
- package/dist/{chunk-RBDW4S6F.js.map → chunk-YEMRRMJQ.js.map} +1 -1
- package/dist/index.cjs +360 -62
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +84 -20
- package/dist/index.d.ts +84 -20
- package/dist/index.js +119 -357
- package/dist/index.js.map +1 -1
- package/dist/node.cjs +27 -6
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +8 -2
- package/dist/node.d.ts +8 -2
- package/dist/node.js +26 -6
- package/dist/node.js.map +1 -1
- package/dist/{plugin-CmPOFVmn.d.ts → plugin-C9Hoxus2.d.ts} +37 -9
- package/dist/{plugin-f5KaFWSN.d.cts → plugin-CiMsGlQe.d.cts} +37 -9
- package/dist/plugins/digests.d.cts +1 -1
- package/dist/plugins/digests.d.ts +1 -1
- package/dist/plugins/preferences-client.cjs.map +1 -1
- package/dist/plugins/preferences-client.d.cts +1 -1
- package/dist/plugins/preferences-client.d.ts +1 -1
- package/dist/plugins/preferences-client.js +1 -1
- package/dist/plugins/preferences.cjs +100 -15
- package/dist/plugins/preferences.cjs.map +1 -1
- package/dist/plugins/preferences.d.cts +3 -1
- package/dist/plugins/preferences.d.ts +3 -1
- package/dist/plugins/preferences.js +35 -7
- package/dist/plugins/preferences.js.map +1 -1
- package/dist/plugins/push.cjs +197 -38
- package/dist/plugins/push.cjs.map +1 -1
- package/dist/plugins/push.d.cts +32 -10
- package/dist/plugins/push.d.ts +32 -10
- package/dist/plugins/push.js +140 -39
- package/dist/plugins/push.js.map +1 -1
- package/dist/providers/web-push.cjs +37 -11
- package/dist/providers/web-push.cjs.map +1 -1
- package/dist/providers/web-push.d.cts +8 -2
- package/dist/providers/web-push.d.ts +8 -2
- package/dist/providers/web-push.js +37 -12
- package/dist/providers/web-push.js.map +1 -1
- package/dist/schema.cjs +2 -1
- package/dist/schema.cjs.map +1 -1
- package/dist/schema.d.cts +6 -1
- package/dist/schema.d.ts +6 -1
- package/dist/schema.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-BV3U542P.js.map +0 -1
- package/dist/chunk-NYDVNMKG.js.map +0 -1
- package/dist/chunk-OZSOIX23.js.map +0 -1
- package/dist/chunk-W3BMEPPQ.js +0 -50
- package/dist/chunk-W3BMEPPQ.js.map +0 -1
|
@@ -24,6 +24,33 @@ type Logger = {
|
|
|
24
24
|
};
|
|
25
25
|
declare const consoleLogger: Logger;
|
|
26
26
|
|
|
27
|
+
type TokenClaims = {
|
|
28
|
+
/** Subject — the user the token acts for. */
|
|
29
|
+
uid: string;
|
|
30
|
+
/** What the token is allowed to do. Verification requires an exact match. */
|
|
31
|
+
purpose: string;
|
|
32
|
+
/** Expiry, epoch seconds. */
|
|
33
|
+
exp: number;
|
|
34
|
+
/** Issued at, epoch seconds. Set by signToken; lets a route refuse a token older than a later change. */
|
|
35
|
+
iat?: number;
|
|
36
|
+
/** Free-form, purpose-specific. */
|
|
37
|
+
data?: Record<string, string>;
|
|
38
|
+
};
|
|
39
|
+
declare function signToken(secret: string, claims: TokenClaims, now?: Date): Promise<string>;
|
|
40
|
+
/** null for every failure mode. Distinguishing them tells an attacker which part to fix. */
|
|
41
|
+
declare function verifyToken(secret: string, token: string, purpose: string, now?: Date): Promise<TokenClaims | null>;
|
|
42
|
+
declare const DEFAULT_TOKEN_TTL_SECONDS: number;
|
|
43
|
+
/** Ninety days. A link that must outlive this should be re-issued, not made immortal. */
|
|
44
|
+
declare const MAX_TOKEN_TTL_SECONDS: number;
|
|
45
|
+
declare const expiresIn: (seconds: number, now?: Date) => number;
|
|
46
|
+
type SignRequest = {
|
|
47
|
+
uid: string;
|
|
48
|
+
purpose: string;
|
|
49
|
+
data?: Record<string, string>;
|
|
50
|
+
/** Defaults to 30 days, capped at 90. */
|
|
51
|
+
ttlSeconds?: number;
|
|
52
|
+
};
|
|
53
|
+
|
|
27
54
|
type Promisable<T> = T | Promise<T>;
|
|
28
55
|
type PrepareContext = {
|
|
29
56
|
type: string;
|
|
@@ -150,12 +177,7 @@ type RouteContext = {
|
|
|
150
177
|
/** Resolved for user-scoped routes, so a handler cannot forget to scope. */
|
|
151
178
|
userId: string | null;
|
|
152
179
|
/** Verified before dispatch, so a handler cannot forget to check. */
|
|
153
|
-
claims:
|
|
154
|
-
uid: string;
|
|
155
|
-
purpose: string;
|
|
156
|
-
exp: number;
|
|
157
|
-
data?: Record<string, string>;
|
|
158
|
-
} | null;
|
|
180
|
+
claims: TokenClaims | null;
|
|
159
181
|
params: Record<string, string>;
|
|
160
182
|
};
|
|
161
183
|
type RouteDefinition = {
|
|
@@ -168,9 +190,15 @@ type RouteDefinition = {
|
|
|
168
190
|
type PluginInitContext = {
|
|
169
191
|
/** Scoped to the tables this plugin declares in schema(). */
|
|
170
192
|
store: PluginStore;
|
|
171
|
-
/**
|
|
172
|
-
|
|
193
|
+
/**
|
|
194
|
+
* Mints tokens for this plugin's own `signed` routes and nothing else. The
|
|
195
|
+
* master secret itself is never handed out: a plugin cannot forge another
|
|
196
|
+
* plugin's links, or anything a future signed flow relies on.
|
|
197
|
+
*/
|
|
198
|
+
sign: (request: SignRequest) => Promise<string>;
|
|
173
199
|
logger: Logger;
|
|
200
|
+
/** Configured notification names, so a route can refuse to store rows for types that do not exist. */
|
|
201
|
+
notificationTypes: readonly string[];
|
|
174
202
|
/** The app's resolver, for plugins that need timezones or addresses. */
|
|
175
203
|
getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;
|
|
176
204
|
/**
|
|
@@ -214,4 +242,4 @@ type ExtractActions<TPlugin> = TPlugin extends {
|
|
|
214
242
|
/** Indexes the tuple rather than recursing: a fold blows the instantiation depth limit. */
|
|
215
243
|
type ActionsOf<TPlugins extends readonly AnyClientPlugin[]> = UnionToIntersection<ExtractActions<TPlugins[number]>>;
|
|
216
244
|
|
|
217
|
-
export { type AnyPlugin as A, type BeforeSendContext as B, type ChannelDecision as C, EasyPingError as E, type FieldDeclaration as F, type Logger as L, type
|
|
245
|
+
export { type AnyPlugin as A, type BeforeSendContext as B, type ChannelDecision as C, DEFAULT_TOKEN_TTL_SECONDS as D, EasyPingError as E, type FieldDeclaration as F, type Logger as L, MAX_TOKEN_TTL_SECONDS as M, type Promisable as P, type RouteScope as R, type SchemaDeclaration as S, type TableDeclaration as T, type UnionToIntersection as U, ValidationError as V, type ActionsOf as a, type AfterDeliverContext as b, type AnyClientPlugin as c, type BeforeSendResult as d, type ClientFetch as e, type ClientPlugin as f, ConfigError as g, type EasyPingPlugin as h, type FieldType as i, type PluginHooks as j, type PrepareContext as k, type ResolveChannelsContext as l, type RouteContext as m, type RouteDefinition as n, type SignRequest as o, type TokenClaims as p, consoleLogger as q, defineClientPlugin as r, definePlugin as s, expiresIn as t, signToken as u, verifyToken as v };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/plugin.ts","../../src/plugins/preferences/client.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"sources":["../../src/core/plugin.ts","../../src/plugins/preferences/client.ts"],"names":[],"mappings":";;;AA2MO,SAAS,mBACd,MAAA,EAC6B;AAC7B,EAAA,OAAO,MAAA;AACT;;;AC3LO,IAAM,iBAAA,GAAoB,MAC/B,kBAAA,CAAmB;AAAA,EACjB,EAAA,EAAI,aAAA;AAAA,EACJ,oBAAoB,EAAC;AAAA,EAErB,OAAA,EAAS,CAAC,KAAA,MAAW;AAAA,IACnB,eAAA,EAAiB,YAId,MAAM,KAAA,CAAM,cAAc,CAAA;AAAA,IAK7B,gBAAA,EAAkB,OAAO,KAAA,KACtB,MAAM,MAAM,cAAA,EAAgB;AAAA,MAC3B,MAAA,EAAQ,MAAA;AAAA,MACR,IAAA,EAAM,IAAA,CAAK,SAAA,CAAU,KAAK;AAAA,KAC3B;AAAA,GACL;AACF,CAAC","file":"preferences-client.cjs","sourcesContent":["import type { DeliveryOutcome } from \"./adapter\";\nimport type { Logger } from \"./errors\";\nimport type { PluginStore } from \"./store\";\nimport type { SignRequest, TokenClaims } from \"./tokens\";\nimport type { Channel, Recipient } from \"./types\";\n\nexport type Promisable<T> = T | Promise<T>;\n\nexport type PrepareContext = {\n type: string;\n recipients: readonly Recipient[];\n};\n\nexport type BeforeSendContext = {\n type: string;\n recipient: Recipient;\n payload: unknown;\n actorId: string | null;\n dedupeKey: string | null;\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type BeforeSendResult =\n | { action: \"continue\"; payload?: unknown; dedupeKey?: string }\n | { action: \"cancel\"; reason: string };\n\nexport type ChannelDecision = {\n channel: Channel;\n action: \"send\" | \"skip\" | \"defer\";\n /** defer only. Written to notification_delivery.not_before. */\n notBefore?: Date | undefined;\n};\n\nexport type ResolveChannelsContext = {\n type: string;\n recipient: Recipient;\n payload: unknown;\n decisions: readonly ChannelDecision[];\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type DeliverContext = {\n channel: Channel;\n deliveryId: string;\n attempt: number;\n recipient: Recipient;\n notification: { id: string; userId: string; type: string; payload: unknown };\n /** Aborted on the runner's timeout. */\n signal: AbortSignal;\n};\n\nexport type AfterSendContext = {\n type: string;\n payload: unknown;\n /** Committed rows. Ids exist only at this point. */\n notifications: readonly { id: string; userId: string }[];\n /** Whatever this plugin's own prepare() returned for this send. */\n prepared: unknown;\n};\n\nexport type AfterDeliverContext = {\n deliveryId: string;\n notificationId: string;\n userId: string;\n channel: Channel;\n outcome: DeliveryOutcome;\n attempt: number;\n isTerminal: boolean;\n};\n\n/** beforeSend and resolveChannels fail closed; afterDeliver fails open. */\nexport type PluginHooks = {\n /** Once per send, for bulk loading — the per-recipient hooks would be an N+1. */\n prepare?: (ctx: PrepareContext) => Promisable<unknown>;\n beforeSend?: (ctx: BeforeSendContext) => Promisable<BeforeSendResult>;\n resolveChannels?: (ctx: ResolveChannelsContext) => Promisable<readonly ChannelDecision[]>;\n /**\n * Once per send, after the rows are committed. The only hook that sees\n * notification ids, which digests needs to bucket an entry against one.\n * Fails open: the notification is already written.\n */\n afterSend?: (ctx: AfterSendContext) => Promisable<void>;\n /**\n * Delivers one of the plugin's declared `channels`. Core carries inApp and\n * email; everything else arrives here, which is how push, sms and slack are\n * added without core learning about them.\n */\n deliver?: (ctx: DeliverContext) => Promisable<DeliveryOutcome>;\n afterDeliver?: (ctx: AfterDeliverContext) => Promisable<void>;\n};\n\nexport type FieldType = \"string\" | \"number\" | \"boolean\" | \"date\" | \"json\";\n\nexport type FieldDeclaration = {\n type: FieldType;\n required?: boolean;\n default?: string | number | boolean;\n /** date fields only. Renders as defaultNow() / CURRENT_TIMESTAMP. */\n defaultNow?: boolean;\n};\n\nexport type IndexDeclaration = {\n on: readonly string[];\n unique?: boolean;\n name?: string;\n};\n\nexport type TableDeclaration = {\n tableName: string;\n fields: Record<string, FieldDeclaration>;\n primaryKey?: readonly string[];\n indexes?: readonly IndexDeclaration[];\n};\n\nexport type SchemaDeclaration = Record<string, TableDeclaration>;\n\nexport type RouteScope =\n | { type: \"user\" }\n | { type: \"machine\" }\n | { type: \"signed\"; purpose: string }\n | { type: \"custom\"; justification: string };\n\nexport type RouteContext = {\n request: Request;\n /** Resolved for user-scoped routes, so a handler cannot forget to scope. */\n userId: string | null;\n /** Verified before dispatch, so a handler cannot forget to check. */\n claims: TokenClaims | null;\n params: Record<string, string>;\n};\n\nexport type RouteDefinition = {\n path: string;\n method: \"GET\" | \"POST\";\n scope: RouteScope;\n handler: (ctx: RouteContext) => Promise<Response>;\n};\n\n/** Handed to a plugin at startup so it need not be given the database twice. */\nexport type PluginInitContext = {\n /** Scoped to the tables this plugin declares in schema(). */\n store: PluginStore;\n /**\n * Mints tokens for this plugin's own `signed` routes and nothing else. The\n * master secret itself is never handed out: a plugin cannot forge another\n * plugin's links, or anything a future signed flow relies on.\n */\n sign: (request: SignRequest) => Promise<string>;\n logger: Logger;\n /** Configured notification names, so a route can refuse to store rows for types that do not exist. */\n notificationTypes: readonly string[];\n /** The app's resolver, for plugins that need timezones or addresses. */\n getRecipients: (userIds: readonly string[]) => Promise<readonly Recipient[]>;\n /**\n * The instance's own send(). A plugin composing a message (a digest, say)\n * routes it back through the pipeline rather than reaching for a provider,\n * so it inherits retry, backoff and idempotency for free.\n */\n send: (\n type: string,\n args: { to: string | readonly string[]; payload: unknown; dedupeKey?: string },\n ) => Promise<unknown>;\n};\n\nexport type EasyPingPlugin<\n TId extends string = string,\n TSchema extends SchemaDeclaration = SchemaDeclaration,\n> = {\n id: TId;\n dependsOn?: readonly string[];\n schema?: TSchema;\n routes?: readonly RouteDefinition[];\n hooks?: PluginHooks;\n /** Channels this plugin delivers. Makes them usable in a notification. */\n channels?: readonly Channel[];\n /** Called once by easyPing() before any hook or route can run. */\n init?: (ctx: PluginInitContext) => void;\n};\n\nexport type AnyPlugin = EasyPingPlugin<string, SchemaDeclaration>;\n\nexport function definePlugin<TId extends string, TSchema extends SchemaDeclaration>(\n plugin: EasyPingPlugin<TId, TSchema>,\n): EasyPingPlugin<TId, TSchema> {\n return plugin;\n}\n\nexport type ClientFetch = (path: string, init?: RequestInit) => Promise<unknown>;\n\nexport type ClientPlugin<\n TId extends string = string,\n TActions extends Record<string, unknown> = Record<string, unknown>,\n> = {\n id: TId;\n /** Phantom. Links client types to the server plugin so a mismatch is a type error. */\n $InferServerPlugin?: AnyPlugin;\n actions: (fetch: ClientFetch) => TActions;\n};\n\nexport type AnyClientPlugin = ClientPlugin<string, Record<string, unknown>>;\n\nexport function defineClientPlugin<TId extends string, TActions extends Record<string, unknown>>(\n plugin: ClientPlugin<TId, TActions>,\n): ClientPlugin<TId, TActions> {\n return plugin;\n}\n\nexport type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (\n k: infer I,\n) => void\n ? I\n : never;\n\n/** Naked type parameter, so the conditional distributes over the union. */\ntype ExtractActions<TPlugin> = TPlugin extends { actions: (fetch: never) => infer TActions }\n ? TActions\n : never;\n\n/** Indexes the tuple rather than recursing: a fold blows the instantiation depth limit. */\nexport type ActionsOf<TPlugins extends readonly AnyClientPlugin[]> = UnionToIntersection<\n ExtractActions<TPlugins[number]>\n>;\n","import { defineClientPlugin } from \"../../core/plugin\";\nimport type { Channel, Frequency } from \"../../core/types\";\nimport type { preferences } from \"./index\";\n\nexport type PreferenceView = {\n userId: string;\n type: string;\n channel: Channel;\n enabled: boolean;\n frequency: Frequency;\n};\n\nexport type UpdatePreferenceInput = {\n type: string;\n channel: Channel;\n enabled?: boolean;\n frequency?: Frequency;\n};\n\n/** Paired by phantom type: importing the server plugin's value would bundle the DB. */\nexport const preferencesClient = () =>\n defineClientPlugin({\n id: \"preferences\",\n $InferServerPlugin: {} as ReturnType<typeof preferences>,\n\n actions: (fetch) => ({\n listPreferences: async (): Promise<{\n preferences: PreferenceView[];\n defaultEnabled: boolean;\n }> =>\n (await fetch(\"/preferences\")) as {\n preferences: PreferenceView[];\n defaultEnabled: boolean;\n },\n\n updatePreference: async (input: UpdatePreferenceInput): Promise<{ ok: boolean }> =>\n (await fetch(\"/preferences\", {\n method: \"POST\",\n body: JSON.stringify(input),\n })) as { ok: boolean },\n }),\n });\n\nexport type PreferencesClient = ReturnType<typeof preferencesClient>;\n"]}
|
|
@@ -10,26 +10,87 @@ function encodeBase64Url(input) {
|
|
|
10
10
|
|
|
11
11
|
// src/core/tokens.ts
|
|
12
12
|
var encoder = new TextEncoder();
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
13
|
+
var KEY_SALT = encoder.encode("easy-ping/tokens/v1");
|
|
14
|
+
async function hmacKey(secret, purpose) {
|
|
15
|
+
const master = await crypto.subtle.importKey("raw", encoder.encode(secret), "HKDF", false, [
|
|
16
|
+
"deriveKey"
|
|
17
|
+
]);
|
|
18
|
+
return crypto.subtle.deriveKey(
|
|
19
|
+
{ name: "HKDF", hash: "SHA-256", salt: KEY_SALT, info: encoder.encode(purpose) },
|
|
20
|
+
master,
|
|
21
|
+
{ name: "HMAC", hash: "SHA-256", length: 256 },
|
|
18
22
|
false,
|
|
19
23
|
["sign", "verify"]
|
|
20
24
|
);
|
|
21
25
|
}
|
|
22
|
-
async function signToken(secret, claims) {
|
|
23
|
-
const
|
|
24
|
-
const
|
|
26
|
+
async function signToken(secret, claims, now = /* @__PURE__ */ new Date()) {
|
|
27
|
+
const stamped = { ...claims, iat: claims.iat ?? Math.floor(now.getTime() / 1e3) };
|
|
28
|
+
const body = encodeBase64Url(JSON.stringify(stamped));
|
|
29
|
+
const signature = await crypto.subtle.sign(
|
|
30
|
+
"HMAC",
|
|
31
|
+
await hmacKey(secret, claims.purpose),
|
|
32
|
+
encoder.encode(body)
|
|
33
|
+
);
|
|
25
34
|
return `${body}.${encodeBase64Url(new Uint8Array(signature))}`;
|
|
26
35
|
}
|
|
27
36
|
var DEFAULT_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;
|
|
28
|
-
var
|
|
37
|
+
var MAX_TOKEN_TTL_SECONDS = 90 * 24 * 60 * 60;
|
|
38
|
+
var expiresIn = (seconds, now = /* @__PURE__ */ new Date()) => Math.floor(now.getTime() / 1e3) + Math.min(Math.max(seconds, 0), MAX_TOKEN_TTL_SECONDS);
|
|
39
|
+
|
|
40
|
+
// src/core/handler.ts
|
|
41
|
+
var MAX_BODY_BYTES = 64 * 1024;
|
|
42
|
+
var PRIVATE_HEADERS = {
|
|
43
|
+
"cache-control": "private, no-store",
|
|
44
|
+
"x-content-type-options": "nosniff"
|
|
45
|
+
};
|
|
46
|
+
var json = (body, status = 200) => new Response(JSON.stringify(body), {
|
|
47
|
+
status,
|
|
48
|
+
headers: { "content-type": "application/json", ...PRIVATE_HEADERS }
|
|
49
|
+
});
|
|
50
|
+
new TextEncoder();
|
|
51
|
+
async function readJsonBody(request, maxBytes = MAX_BODY_BYTES) {
|
|
52
|
+
const tooLarge = () => ({ error: json({ error: `body exceeds ${maxBytes} bytes` }, 413) });
|
|
53
|
+
const declared = Number(request.headers.get("content-length"));
|
|
54
|
+
if (Number.isFinite(declared) && declared > maxBytes) return tooLarge();
|
|
55
|
+
if (!request.body) return { body: {} };
|
|
56
|
+
const reader = request.body.getReader();
|
|
57
|
+
const chunks = [];
|
|
58
|
+
let total = 0;
|
|
59
|
+
for (; ; ) {
|
|
60
|
+
const { done, value } = await reader.read();
|
|
61
|
+
if (done) break;
|
|
62
|
+
total += value.byteLength;
|
|
63
|
+
if (total > maxBytes) {
|
|
64
|
+
await reader.cancel();
|
|
65
|
+
return tooLarge();
|
|
66
|
+
}
|
|
67
|
+
chunks.push(value);
|
|
68
|
+
}
|
|
69
|
+
const bytes = new Uint8Array(total);
|
|
70
|
+
let offset = 0;
|
|
71
|
+
for (const chunk of chunks) {
|
|
72
|
+
bytes.set(chunk, offset);
|
|
73
|
+
offset += chunk.byteLength;
|
|
74
|
+
}
|
|
75
|
+
const text = new TextDecoder().decode(bytes);
|
|
76
|
+
if (text.trim() === "") return { body: {} };
|
|
77
|
+
try {
|
|
78
|
+
const parsed = JSON.parse(text);
|
|
79
|
+
return {
|
|
80
|
+
body: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}
|
|
81
|
+
};
|
|
82
|
+
} catch {
|
|
83
|
+
return { error: json({ error: "body must be a JSON object" }, 400) };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
29
86
|
|
|
30
87
|
// src/plugins/preferences/index.ts
|
|
31
88
|
var UNSUBSCRIBE_PURPOSE = "unsubscribe";
|
|
32
89
|
var TABLE = "notification_preference";
|
|
90
|
+
var CHANNELS = ["inApp", "email", "push", "sms", "slack"];
|
|
91
|
+
var FREQUENCIES = ["instant", "daily", "weekly", "off"];
|
|
92
|
+
var isChannel = (value) => CHANNELS.includes(value);
|
|
93
|
+
var isFrequency = (value) => FREQUENCIES.includes(value);
|
|
33
94
|
var key = (userId, type, channel) => `${userId} ${type} ${channel}`;
|
|
34
95
|
function buildUnsubscribeToken(secret, userId, type, channel, ttlSeconds = DEFAULT_TOKEN_TTL_SECONDS) {
|
|
35
96
|
return signToken(secret, {
|
|
@@ -48,7 +109,9 @@ function preferences(options = {}) {
|
|
|
48
109
|
return row ? row.enabled && row.frequency !== "off" : defaultEnabled;
|
|
49
110
|
};
|
|
50
111
|
const load = (userIds) => ctx.store.find(TABLE, { userId: { in: [...userIds] } });
|
|
51
|
-
const save = (row) => ctx.store.upsert(TABLE, [row
|
|
112
|
+
const save = (row) => ctx.store.upsert(TABLE, [{ ...row, updatedAt: /* @__PURE__ */ new Date() }], {
|
|
113
|
+
onConflict: ["userId", "type", "channel"]
|
|
114
|
+
});
|
|
52
115
|
return {
|
|
53
116
|
id: "preferences",
|
|
54
117
|
init: (context) => {
|
|
@@ -62,7 +125,8 @@ function preferences(options = {}) {
|
|
|
62
125
|
type: { type: "string", required: true },
|
|
63
126
|
channel: { type: "string", required: true },
|
|
64
127
|
enabled: { type: "boolean", required: true, default: true },
|
|
65
|
-
frequency: { type: "string", required: true, default: "instant" }
|
|
128
|
+
frequency: { type: "string", required: true, default: "instant" },
|
|
129
|
+
updatedAt: { type: "date", required: true, defaultNow: true }
|
|
66
130
|
},
|
|
67
131
|
primaryKey: ["userId", "type", "channel"]
|
|
68
132
|
}
|
|
@@ -100,9 +164,19 @@ function preferences(options = {}) {
|
|
|
100
164
|
method: "POST",
|
|
101
165
|
scope: { type: "user" },
|
|
102
166
|
handler: async ({ request, userId }) => {
|
|
103
|
-
const
|
|
104
|
-
if (
|
|
105
|
-
|
|
167
|
+
const parsed = await readJsonBody(request);
|
|
168
|
+
if ("error" in parsed) return parsed.error;
|
|
169
|
+
const body = parsed.body;
|
|
170
|
+
const bad = (error) => Response.json({ error }, { status: 400 });
|
|
171
|
+
if (typeof body.type !== "string" || !ctx.notificationTypes.includes(body.type)) {
|
|
172
|
+
return bad("type must be a configured notification type");
|
|
173
|
+
}
|
|
174
|
+
if (!isChannel(body.channel)) return bad(`channel must be one of ${CHANNELS.join(", ")}`);
|
|
175
|
+
if (body.enabled !== void 0 && typeof body.enabled !== "boolean") {
|
|
176
|
+
return bad("enabled must be a boolean");
|
|
177
|
+
}
|
|
178
|
+
if (body.frequency !== void 0 && !isFrequency(body.frequency)) {
|
|
179
|
+
return bad(`frequency must be one of ${FREQUENCIES.join(", ")}`);
|
|
106
180
|
}
|
|
107
181
|
await save({
|
|
108
182
|
userId: userId ?? "",
|
|
@@ -123,7 +197,18 @@ function preferences(options = {}) {
|
|
|
123
197
|
handler: async ({ claims }) => {
|
|
124
198
|
const type = claims?.data?.type;
|
|
125
199
|
const channel = claims?.data?.channel;
|
|
126
|
-
if (!claims || !type || !channel) {
|
|
200
|
+
if (!claims || !type || !isChannel(channel)) {
|
|
201
|
+
return Response.json({ error: "invalid token" }, { status: 400 });
|
|
202
|
+
}
|
|
203
|
+
const [current] = await ctx.store.find(
|
|
204
|
+
TABLE,
|
|
205
|
+
{ userId: claims.uid, type, channel },
|
|
206
|
+
{ limit: 1 }
|
|
207
|
+
);
|
|
208
|
+
if (current && !current.enabled && current.frequency === "off") {
|
|
209
|
+
return Response.json({ ok: true, unsubscribed: { type, channel } });
|
|
210
|
+
}
|
|
211
|
+
if (current?.updatedAt && claims.iat !== void 0 && current.updatedAt.getTime() > (claims.iat + 1) * 1e3) {
|
|
127
212
|
return Response.json({ error: "invalid token" }, { status: 400 });
|
|
128
213
|
}
|
|
129
214
|
await save({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/core/base64url.ts","../../src/core/tokens.ts","../../src/plugins/preferences/index.ts"],"names":[],"mappings":";;;AAEO,SAAS,gBAAgB,KAAA,EAAoC;AAClE,EAAA,MAAM,KAAA,GAAQ,OAAO,KAAA,KAAU,QAAA,GAAW,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,KAAK,CAAA,GAAI,KAAA;AAC5E,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,EAAO,MAAA,IAAU,MAAA,CAAO,aAAa,IAAI,CAAA;AAC5D,EAAA,OAAO,IAAA,CAAK,MAAM,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/E;;;ACMA,IAAM,OAAA,GAAU,IAAI,WAAA,EAAY;AAEhC,eAAe,QAAQ,MAAA,EAAoC;AACzD,EAAA,OAAO,OAAO,MAAA,CA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eBase64Url(input: string | Uint8Array): string {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n// Uint8Array<ArrayBuffer>: bare Uint8Array widens and is not a BufferSource.\nexport function decodeBase64UrlBytes(value: string): Uint8Array<ArrayBuffer> | null {\n try {\n const binary = atob(value.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\nexport function decodeBase64Url(value: string): string | null {\n const bytes = decodeBase64UrlBytes(value);\n return bytes ? new TextDecoder().decode(bytes) : null;\n}\n","import { decodeBase64Url, decodeBase64UrlBytes, encodeBase64Url } from \"./base64url\";\n\nexport type TokenClaims = {\n /** Subject — the user the token acts for. */\n uid: string;\n /** What the token is allowed to do. Verification requires an exact match. */\n purpose: string;\n /** Expiry, epoch seconds. */\n exp: number;\n /** Free-form, purpose-specific. */\n data?: Record<string, string>;\n};\n\nconst encoder = new TextEncoder();\n\nasync function hmacKey(secret: string): Promise<CryptoKey> {\n return crypto.subtle.importKey(\n \"raw\",\n encoder.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\", \"verify\"],\n );\n}\n\nexport async function signToken(secret: string, claims: TokenClaims): Promise<string> {\n const body = encodeBase64Url(JSON.stringify(claims));\n const signature = await crypto.subtle.sign(\"HMAC\", await hmacKey(secret), encoder.encode(body));\n return `${body}.${encodeBase64Url(new Uint8Array(signature))}`;\n}\n\n/** null for every failure mode. Distinguishing them tells an attacker which part to fix. */\nexport async function verifyToken(\n secret: string,\n token: string,\n purpose: string,\n now: Date = new Date(),\n): Promise<TokenClaims | null> {\n const separator = token.lastIndexOf(\".\");\n if (separator <= 0) return null;\n\n const body = token.slice(0, separator);\n const signature = decodeBase64UrlBytes(token.slice(separator + 1));\n if (!signature) return null;\n\n // crypto.subtle.verify is constant-time.\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n await hmacKey(secret),\n signature,\n encoder.encode(body),\n );\n if (!valid) return null;\n\n const decoded = decodeBase64Url(body);\n if (!decoded) return null;\n\n let claims: TokenClaims;\n try {\n claims = JSON.parse(decoded) as TokenClaims;\n } catch {\n return null;\n }\n\n if (typeof claims?.uid !== \"string\" || typeof claims.exp !== \"number\") return null;\n // Scoped so an unsubscribe token can never be replayed against another route.\n if (claims.purpose !== purpose) return null;\n if (claims.exp * 1000 <= now.getTime()) return null;\n\n return claims;\n}\n\nexport const DEFAULT_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;\n\nexport const expiresIn = (seconds: number, now: Date = new Date()): number =>\n Math.floor(now.getTime() / 1000) + seconds;\n","import type {\n ChannelDecision,\n EasyPingPlugin,\n PluginInitContext,\n PrepareContext,\n ResolveChannelsContext,\n} from \"../../core/plugin\";\nimport { DEFAULT_TOKEN_TTL_SECONDS, expiresIn, signToken } from \"../../core/tokens\";\nimport type { Channel, Frequency } from \"../../core/types\";\n\nexport const UNSUBSCRIBE_PURPOSE = \"unsubscribe\";\n\nconst TABLE = \"notification_preference\";\n\nexport type PreferenceRow = {\n userId: string;\n type: string;\n channel: Channel;\n enabled: boolean;\n frequency: Frequency;\n};\n\nexport type PreferencesOptions = {\n /** What an absent row means. Flip to false for opt-in-only notifications. */\n defaultEnabled?: boolean;\n /** Types that ignore preferences entirely: receipts, security alerts. */\n alwaysSend?: readonly string[];\n unsubscribeTtlSeconds?: number;\n};\n\nconst key = (userId: string, type: string, channel: string) => `${userId} ${type} ${channel}`;\n\ntype PreparedPreferences = Map<string, PreferenceRow>;\n\nexport function buildUnsubscribeToken(\n secret: string,\n userId: string,\n type: string,\n channel: Channel,\n ttlSeconds = DEFAULT_TOKEN_TTL_SECONDS,\n): Promise<string> {\n return signToken(secret, {\n uid: userId,\n purpose: UNSUBSCRIBE_PURPOSE,\n exp: expiresIn(ttlSeconds),\n data: { type, channel },\n });\n}\n\nexport function preferences(options: PreferencesOptions = {}): EasyPingPlugin<\"preferences\"> {\n const defaultEnabled = options.defaultEnabled ?? true;\n const alwaysSend = new Set(options.alwaysSend ?? []);\n\n // Assigned by init(), which easyPing() runs before any hook or route.\n let ctx: PluginInitContext;\n\n const isAllowed = (userId: string, type: string, channel: Channel, rows: PreparedPreferences) => {\n const row = rows.get(key(userId, type, channel));\n return row ? row.enabled && row.frequency !== \"off\" : defaultEnabled;\n };\n\n const load = (userIds: readonly string[]) =>\n ctx.store.find<PreferenceRow>(TABLE, { userId: { in: [...userIds] } });\n\n const save = (row: PreferenceRow) =>\n ctx.store.upsert(TABLE, [row], { onConflict: [\"userId\", \"type\", \"channel\"] });\n\n return {\n id: \"preferences\",\n\n init: (context) => {\n ctx = context;\n },\n\n schema: {\n notificationPreference: {\n tableName: TABLE,\n fields: {\n userId: { type: \"string\", required: true },\n type: { type: \"string\", required: true },\n channel: { type: \"string\", required: true },\n enabled: { type: \"boolean\", required: true, default: true },\n frequency: { type: \"string\", required: true, default: \"instant\" },\n },\n primaryKey: [\"userId\", \"type\", \"channel\"],\n },\n },\n\n hooks: {\n /** One query per send; doing this per recipient would be an N+1. */\n prepare: async (context: PrepareContext): Promise<PreparedPreferences> => {\n if (alwaysSend.has(context.type)) return new Map();\n\n const rows = await load(context.recipients.map((recipient) => recipient.userId));\n return new Map(rows.map((row) => [key(row.userId, row.type, row.channel), row]));\n },\n\n resolveChannels: (context: ResolveChannelsContext) => {\n if (alwaysSend.has(context.type)) return context.decisions;\n\n // prepare() failing leaves this undefined. Fail closed rather than\n // assuming everyone opted in: that is exactly how people who\n // unsubscribed get emailed anyway.\n if (!(context.prepared instanceof Map)) {\n return context.decisions.map((decision) => ({ ...decision, action: \"skip\" as const }));\n }\n\n const rows = context.prepared as PreparedPreferences;\n\n return context.decisions.map<ChannelDecision>((decision) =>\n isAllowed(context.recipient.userId, context.type, decision.channel, rows)\n ? decision\n : { ...decision, action: \"skip\" },\n );\n },\n },\n\n routes: [\n {\n path: \"/preferences\",\n method: \"GET\",\n scope: { type: \"user\" },\n handler: async ({ userId }) => {\n const rows = await load([userId ?? \"\"]);\n return Response.json({ preferences: rows, defaultEnabled });\n },\n },\n\n {\n path: \"/preferences\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const body = (await request.json().catch(() => null)) as Partial<PreferenceRow> | null;\n\n if (!body?.type || !body.channel) {\n return Response.json({ error: \"type and channel are required\" }, { status: 400 });\n }\n\n // userId comes from the resolved session, never from the body.\n await save({\n userId: userId ?? \"\",\n type: body.type,\n channel: body.channel,\n enabled: body.enabled ?? true,\n frequency: body.frequency ?? \"instant\",\n });\n\n return Response.json({ ok: true });\n },\n },\n\n {\n // Reached from a mail client with no session, so it is authenticated\n // by the signature on the link itself.\n path: \"/unsubscribe\",\n method: \"POST\",\n scope: { type: \"signed\", purpose: UNSUBSCRIBE_PURPOSE },\n handler: async ({ claims }) => {\n const type = claims?.data?.type;\n const channel = claims?.data?.channel as Channel | undefined;\n if (!claims || !type || !channel) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n await save({\n userId: claims.uid,\n type,\n channel,\n enabled: false,\n frequency: \"off\",\n });\n\n // Gmail and Yahoo one-click requires the POST itself to unsubscribe,\n // with no confirmation page.\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n },\n },\n ],\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/core/base64url.ts","../../src/core/tokens.ts","../../src/core/handler.ts","../../src/plugins/preferences/index.ts"],"names":[],"mappings":";;;AAEO,SAAS,gBAAgB,KAAA,EAAoC;AAClE,EAAA,MAAM,KAAA,GAAQ,OAAO,KAAA,KAAU,QAAA,GAAW,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,KAAK,CAAA,GAAI,KAAA;AAC5E,EAAA,IAAI,MAAA,GAAS,EAAA;AACb,EAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,EAAO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,EAAI,IAAA,EAAM,cAAc,EAAE,IAAA,EAAM,OAAA,EAAQ,EAAG,CAAA;AAAA,QACpE;AAAA;AACF;AACF,GACF;AACF","file":"preferences.cjs","sourcesContent":["// Web APIs, not Buffer: this runs on Workers and Vercel Edge.\n\nexport function encodeBase64Url(input: string | Uint8Array): string {\n const bytes = typeof input === \"string\" ? new TextEncoder().encode(input) : input;\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n// Uint8Array<ArrayBuffer>: bare Uint8Array widens and is not a BufferSource.\nexport function decodeBase64UrlBytes(value: string): Uint8Array<ArrayBuffer> | null {\n try {\n const binary = atob(value.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return Uint8Array.from(binary, (char) => char.charCodeAt(0));\n } catch {\n return null;\n }\n}\n\nexport function decodeBase64Url(value: string): string | null {\n const bytes = decodeBase64UrlBytes(value);\n return bytes ? new TextDecoder().decode(bytes) : null;\n}\n","import { decodeBase64Url, decodeBase64UrlBytes, encodeBase64Url } from \"./base64url\";\n\nexport type TokenClaims = {\n /** Subject — the user the token acts for. */\n uid: string;\n /** What the token is allowed to do. Verification requires an exact match. */\n purpose: string;\n /** Expiry, epoch seconds. */\n exp: number;\n /** Issued at, epoch seconds. Set by signToken; lets a route refuse a token older than a later change. */\n iat?: number;\n /** Free-form, purpose-specific. */\n data?: Record<string, string>;\n};\n\nconst encoder = new TextEncoder();\n\n// Changing this invalidates every outstanding token. Bump it on purpose only.\nconst KEY_SALT = encoder.encode(\"easy-ping/tokens/v1\");\n\n/**\n * One HMAC key per purpose, derived from the master secret with HKDF. A key\n * that can sign unsubscribe links cannot sign anything else, so a plugin\n * handed the unsubscribe key gets exactly that and no more.\n */\nasync function hmacKey(secret: string, purpose: string): Promise<CryptoKey> {\n const master = await crypto.subtle.importKey(\"raw\", encoder.encode(secret), \"HKDF\", false, [\n \"deriveKey\",\n ]);\n return crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: KEY_SALT, info: encoder.encode(purpose) },\n master,\n { name: \"HMAC\", hash: \"SHA-256\", length: 256 },\n false,\n [\"sign\", \"verify\"],\n );\n}\n\nexport async function signToken(\n secret: string,\n claims: TokenClaims,\n now: Date = new Date(),\n): Promise<string> {\n const stamped: TokenClaims = { ...claims, iat: claims.iat ?? Math.floor(now.getTime() / 1000) };\n const body = encodeBase64Url(JSON.stringify(stamped));\n const signature = await crypto.subtle.sign(\n \"HMAC\",\n await hmacKey(secret, claims.purpose),\n encoder.encode(body),\n );\n return `${body}.${encodeBase64Url(new Uint8Array(signature))}`;\n}\n\n/** null for every failure mode. Distinguishing them tells an attacker which part to fix. */\nexport async function verifyToken(\n secret: string,\n token: string,\n purpose: string,\n now: Date = new Date(),\n): Promise<TokenClaims | null> {\n const separator = token.lastIndexOf(\".\");\n if (separator <= 0) return null;\n\n const body = token.slice(0, separator);\n const signature = decodeBase64UrlBytes(token.slice(separator + 1));\n if (!signature) return null;\n\n // Verified under the key for the purpose this route expects, before the\n // body is even parsed. A token minted for another purpose fails here.\n // crypto.subtle.verify is constant-time.\n const valid = await crypto.subtle.verify(\n \"HMAC\",\n await hmacKey(secret, purpose),\n signature,\n encoder.encode(body),\n );\n if (!valid) return null;\n\n const decoded = decodeBase64Url(body);\n if (!decoded) return null;\n\n let claims: TokenClaims;\n try {\n claims = JSON.parse(decoded) as TokenClaims;\n } catch {\n return null;\n }\n\n if (typeof claims?.uid !== \"string\" || typeof claims.exp !== \"number\") return null;\n if (claims.purpose !== purpose) return null;\n if (claims.exp * 1000 <= now.getTime()) return null;\n if (claims.iat !== undefined && typeof claims.iat !== \"number\") return null;\n\n if (claims.data !== undefined) {\n if (typeof claims.data !== \"object\" || claims.data === null || Array.isArray(claims.data)) {\n return null;\n }\n for (const value of Object.values(claims.data)) {\n if (typeof value !== \"string\") return null;\n }\n }\n\n return claims;\n}\n\nexport const DEFAULT_TOKEN_TTL_SECONDS = 30 * 24 * 60 * 60;\n/** Ninety days. A link that must outlive this should be re-issued, not made immortal. */\nexport const MAX_TOKEN_TTL_SECONDS = 90 * 24 * 60 * 60;\n\nexport const expiresIn = (seconds: number, now: Date = new Date()): number =>\n Math.floor(now.getTime() / 1000) + Math.min(Math.max(seconds, 0), MAX_TOKEN_TTL_SECONDS);\n\nexport type SignRequest = {\n uid: string;\n purpose: string;\n data?: Record<string, string>;\n /** Defaults to 30 days, capped at 90. */\n ttlSeconds?: number;\n};\n\n/**\n * What a plugin gets instead of the secret: a signer that only mints tokens\n * for the purposes its own `signed` routes declared.\n */\nexport function createScopedSigner(\n secret: string,\n pluginId: string,\n purposes: ReadonlySet<string>,\n onViolation: (message: string) => Error,\n): (request: SignRequest) => Promise<string> {\n return (request) => {\n if (!purposes.has(request.purpose)) {\n throw onViolation(\n `plugin \"${pluginId}\" tried to sign a token for purpose \"${request.purpose}\", ` +\n \"which none of its signed routes declare.\",\n );\n }\n return signToken(secret, {\n uid: request.uid,\n purpose: request.purpose,\n exp: expiresIn(request.ttlSeconds ?? DEFAULT_TOKEN_TTL_SECONDS),\n ...(request.data ? { data: request.data } : {}),\n });\n };\n}\n","import type { DatabaseAdapter } from \"./adapter\";\nimport type { SessionConfig } from \"./config\";\nimport type { Logger } from \"./errors\";\nimport type { Promisable, RouteDefinition } from \"./plugin\";\nimport type { Runner } from \"./runner\";\nimport { verifyToken } from \"./tokens\";\n\nexport type HandlerDeps = {\n adapter: DatabaseAdapter;\n session: SessionConfig;\n runner: Runner;\n logger: Logger;\n basePath: string;\n secret: string;\n cronSecret?: string | undefined;\n /** Guards plugin machine routes. The instance defaults it to cronSecret. */\n machineSecret?: string | undefined;\n cronMaxSweeps?: number | undefined;\n pluginRoutes?: readonly RouteDefinition[] | undefined;\n /** Returns a 429 to send, or null to proceed. Runs after onRequest, before routing. */\n rateLimit?: ((request: Request) => Response | null) | undefined;\n /** Origins other than the request's own host that may POST. `*.example.com` allowed. */\n trustedOrigins?: readonly string[] | undefined;\n /** Runs before routing. Returning a Response short-circuits; use it for rate limiting. */\n // biome-ignore lint/suspicious/noConfusingVoidType: a hook that returns nothing is the common case\n onRequest?: ((request: Request) => Promisable<Response | undefined | void>) | undefined;\n maxBodyBytes?: number | undefined;\n};\n\n/** Every JSON body is capped here. Nothing legitimate the routes accept is bigger. */\nexport const MAX_BODY_BYTES = 64 * 1024;\n\nconst MAX_READ_IDS = 200;\n\n// The inbox is per-user data: never let a shared cache keep it, never let a\n// browser sniff it into something executable.\nconst PRIVATE_HEADERS: Record<string, string> = {\n \"cache-control\": \"private, no-store\",\n \"x-content-type-options\": \"nosniff\",\n};\n\nconst json = (body: unknown, status = 200) =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\", ...PRIVATE_HEADERS },\n });\n\nconst empty = (status: number) => new Response(null, { status, headers: PRIVATE_HEADERS });\n\n/** Plugin responses get the same headers, without touching their body. */\nfunction harden(response: Response): Response {\n const headers = new Headers(response.headers);\n for (const [name, value] of Object.entries(PRIVATE_HEADERS)) {\n if (!headers.has(name)) headers.set(name, value);\n }\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\nconst encoder = new TextEncoder();\n\n/**\n * Constant-time comparison over SHA-256 digests. Node's timingSafeEqual is\n * unavailable on edge runtimes, `===` leaks through timing, and comparing the\n * raw strings would still reveal the secret's length.\n */\nasync function timingSafeEqual(a: string, b: string): Promise<boolean> {\n const [left, right] = await Promise.all(\n [a, b].map(\n async (value) => new Uint8Array(await crypto.subtle.digest(\"SHA-256\", encoder.encode(value))),\n ),\n );\n let diff = 0;\n for (let i = 0; i < 32; i += 1) diff |= (left?.[i] ?? 0) ^ (right?.[i] ?? 0);\n return diff === 0;\n}\n\n/** Anchored at a segment boundary: `/foo/api/notifications/cron` is not a cron request. */\nfunction routePath(url: URL, basePath: string): string {\n const { pathname } = url;\n if (pathname === basePath) return \"/\";\n if (pathname.startsWith(`${basePath}/`)) return pathname.slice(basePath.length);\n return pathname;\n}\n\nexport type JsonBody = { body: Record<string, unknown> } | { error: Response };\n\n/**\n * Reads a JSON object body with a byte cap enforced while streaming, so an\n * oversized body is refused before it is buffered. Malformed JSON is 400; an\n * empty body is `{}`. Plugin routes should use this rather than\n * `request.json()`, which has no limit.\n */\nexport async function readJsonBody(\n request: Request,\n maxBytes: number = MAX_BODY_BYTES,\n): Promise<JsonBody> {\n const tooLarge = () => ({ error: json({ error: `body exceeds ${maxBytes} bytes` }, 413) });\n\n const declared = Number(request.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > maxBytes) return tooLarge();\n if (!request.body) return { body: {} };\n\n const reader = request.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.byteLength;\n if (total > maxBytes) {\n await reader.cancel();\n return tooLarge();\n }\n chunks.push(value);\n }\n\n const bytes = new Uint8Array(total);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n const text = new TextDecoder().decode(bytes);\n if (text.trim() === \"\") return { body: {} };\n\n try {\n const parsed: unknown = JSON.parse(text);\n return {\n body:\n parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {},\n };\n } catch {\n return { error: json({ error: \"body must be a JSON object\" }, 400) };\n }\n}\n\nconst isJsonContentType = (request: Request) =>\n /^application\\/json\\s*(;|$)/i.test((request.headers.get(\"content-type\") ?? \"\").trim());\n\nfunction originAllowed(origin: string, url: URL, request: Request, trusted: readonly string[]) {\n let host: string;\n try {\n host = new URL(origin).host;\n } catch {\n return false;\n }\n\n if (host === url.host) return true;\n // Behind a proxy that rewrites Host, the public host arrives here instead.\n const forwarded = request.headers.get(\"x-forwarded-host\")?.split(\",\")[0]?.trim();\n if (forwarded && host === forwarded) return true;\n\n return trusted.some((entry) =>\n entry.startsWith(\"*.\") ? host.endsWith(entry.slice(1)) : entry === origin,\n );\n}\n\n/**\n * Two cheap CSRF defences for cookie-authenticated POSTs. A cross-site form\n * cannot send `application/json` without a preflight the browser will fail,\n * and it cannot forge `Origin`. Neither depends on the host app's SameSite\n * policy, which the library cannot see.\n */\nfunction csrfCheck(request: Request, url: URL, trusted: readonly string[]): Response | null {\n if (!isJsonContentType(request)) {\n return json({ error: \"content-type must be application/json\" }, 415);\n }\n\n const origin = request.headers.get(\"origin\");\n if (origin === null) return null;\n if (origin === \"null\" || !originAllowed(origin, url, request, trusted)) return empty(403);\n\n return null;\n}\n\nexport function createHandler(deps: HandlerDeps) {\n const trustedOrigins = deps.trustedOrigins ?? [];\n const maxBodyBytes = deps.maxBodyBytes ?? MAX_BODY_BYTES;\n\n async function resolveUserId(request: Request): Promise<string | null | \"error\"> {\n try {\n return await deps.session.getUserId(request);\n } catch (error) {\n // A broken session lookup is a 500, never a 401. Collapsing them makes\n // an outage look like a mass logout. RFC 0002 §1.\n deps.logger.error(\"session.getUserId threw\", { error });\n return \"error\";\n }\n }\n\n async function bearerMatches(request: Request, secret: string | undefined): Promise<boolean> {\n if (!secret) return false;\n const header = request.headers.get(\"authorization\") ?? \"\";\n const presented = header.startsWith(\"Bearer \") ? header.slice(7) : header;\n return timingSafeEqual(presented, secret);\n }\n\n async function handleCron(request: Request): Promise<Response> {\n if (!deps.cronSecret) return empty(404);\n if (!(await bearerMatches(request, deps.cronSecret))) return empty(401);\n\n // Bounded: an overlapping scheduler must not hold a request open for as\n // long as the backlog lasts.\n const result = await deps.runner.drain(\n deps.cronMaxSweeps === undefined ? {} : { maxSweeps: deps.cronMaxSweeps },\n );\n return json(result);\n }\n\n /**\n * Plugin routes are dispatched before core ones and carry their scope with\n * them. Authentication happens here rather than in the plugin handler, so a\n * plugin physically cannot forget to check a signature or scope a query.\n */\n async function handlePluginRoute(\n route: RouteDefinition,\n request: Request,\n url: URL,\n ): Promise<Response> {\n if (route.scope.type === \"user\") {\n if (request.method === \"POST\") {\n const rejected = csrfCheck(request, url, trustedOrigins);\n if (rejected) return rejected;\n }\n\n const userId = await resolveUserId(request);\n if (userId === \"error\") return empty(500);\n if (userId === null) return empty(401);\n return harden(await route.handler({ request, userId, claims: null, params: {} }));\n }\n\n if (route.scope.type === \"machine\") {\n if (!deps.machineSecret) return empty(404);\n if (!(await bearerMatches(request, deps.machineSecret))) return empty(401);\n return harden(await route.handler({ request, userId: null, claims: null, params: {} }));\n }\n\n if (route.scope.type === \"signed\") {\n const token =\n url.searchParams.get(\"token\") ??\n (request.headers.get(\"authorization\") ?? \"\").replace(/^Bearer /, \"\");\n\n const claims = await verifyToken(deps.secret, token, route.scope.purpose);\n // One response for every failure mode. Distinguishing expired from\n // forged tells an attacker which part to fix. RFC 0002 §5.\n if (!claims) return empty(400);\n\n return harden(await route.handler({ request, userId: claims.uid, claims, params: {} }));\n }\n\n return harden(await route.handler({ request, userId: null, claims: null, params: {} }));\n }\n\n async function route(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const path = routePath(url, deps.basePath);\n\n if (deps.onRequest) {\n const early = await deps.onRequest(request);\n if (early instanceof Response) return early;\n }\n\n if (deps.rateLimit) {\n const limited = deps.rateLimit(request);\n if (limited) return limited;\n }\n\n if (path === \"/cron\") {\n if (request.method !== \"POST\") return empty(405);\n return handleCron(request);\n }\n\n const pluginRoute = deps.pluginRoutes?.find(\n (candidate) => candidate.path === path && candidate.method === request.method,\n );\n if (pluginRoute) return handlePluginRoute(pluginRoute, request, url);\n\n if (request.method === \"POST\") {\n const rejected = csrfCheck(request, url, trustedOrigins);\n if (rejected) return rejected;\n }\n\n const userId = await resolveUserId(request);\n if (userId === \"error\") return empty(500);\n if (userId === null) return empty(401);\n\n if (request.method === \"GET\" && path === \"/\") {\n const limitParam = Number(url.searchParams.get(\"limit\") ?? 20);\n const limit = Number.isFinite(limitParam) ? Math.min(Math.max(limitParam, 1), 100) : 20;\n const cursor = url.searchParams.get(\"cursor\");\n\n // The badge count rides along with the first page, so a polling client\n // needs one request per tick instead of two. Paginating past the first\n // page omits it: a cursor request is scrollback, not a poll.\n const [page, unseenCount] = await Promise.all([\n deps.adapter.listNotifications({\n userId,\n limit,\n ...(cursor ? { cursor } : {}),\n ...(url.searchParams.get(\"unreadOnly\") === \"true\" ? { unreadOnly: true } : {}),\n }),\n cursor ? Promise.resolve(null) : deps.adapter.countUnseen(userId),\n ]);\n\n return json(unseenCount === null ? page : { ...page, unseenCount });\n }\n\n if (request.method === \"GET\" && path === \"/count\") {\n return json({ unseen: await deps.adapter.countUnseen(userId) });\n }\n\n if (request.method === \"POST\" && path === \"/seen\") {\n const parsed = await readJsonBody(request, maxBodyBytes);\n if (\"error\" in parsed) return parsed.error;\n const before = typeof parsed.body.before === \"string\" ? new Date(parsed.body.before) : null;\n\n // Defaults to now, but a client should send the timestamp of the newest\n // notification it has actually rendered. Otherwise anything that arrived\n // between the last poll and the click is marked seen without ever having\n // produced a badge — the user silently misses it.\n //\n // +1ms because Postgres keeps microseconds while an ISO string carries\n // only milliseconds. Without it the truncated cutoff falls *before* the\n // very row it was taken from, and markSeen matches nothing at all.\n const cutoff =\n before && !Number.isNaN(before.getTime()) ? new Date(before.getTime() + 1) : new Date();\n\n await deps.adapter.markSeen(userId, cutoff);\n return json({ ok: true });\n }\n\n if (request.method === \"POST\" && path === \"/read\") {\n const parsed = await readJsonBody(request, maxBodyBytes);\n if (\"error\" in parsed) return parsed.error;\n const ids = Array.isArray(parsed.body.ids)\n ? parsed.body.ids.filter((id): id is string => typeof id === \"string\")\n : [];\n if (ids.length === 0) return json({ error: \"ids must be a non-empty string array\" }, 400);\n\n // Unbounded, this builds a query with as many bind parameters as the\n // caller cares to send. Postgres caps at 65535 and degrades long before.\n if (ids.length > MAX_READ_IDS) {\n return json({ error: `at most ${MAX_READ_IDS} ids per request` }, 400);\n }\n\n // Scoped by userId in the adapter. A miss is 404, not 403 — a 403 would\n // confirm the row exists and belongs to someone else. RFC 0002 §2.\n const updated = await deps.adapter.markRead(userId, ids);\n return updated === 0 ? empty(404) : json({ updated });\n }\n\n if (request.method === \"POST\" && path === \"/read-all\") {\n return json({ updated: await deps.adapter.markAllRead(userId) });\n }\n\n return empty(404);\n }\n\n async function handle(request: Request): Promise<Response> {\n try {\n return await route(request);\n } catch (error) {\n // Never let a driver error escape: on Node it becomes an unhandled\n // rejection, on other hosts a stack trace in the response body.\n deps.logger.error(\"request failed\", { url: request.url, error });\n return empty(500);\n }\n }\n\n return {\n handle,\n GET: handle,\n POST: handle,\n };\n}\n","import { readJsonBody } from \"../../core/handler\";\nimport type {\n ChannelDecision,\n EasyPingPlugin,\n PluginInitContext,\n PrepareContext,\n ResolveChannelsContext,\n} from \"../../core/plugin\";\nimport { DEFAULT_TOKEN_TTL_SECONDS, expiresIn, signToken } from \"../../core/tokens\";\nimport type { Channel, Frequency } from \"../../core/types\";\n\nexport const UNSUBSCRIBE_PURPOSE = \"unsubscribe\";\n\nconst TABLE = \"notification_preference\";\n\nconst CHANNELS: readonly Channel[] = [\"inApp\", \"email\", \"push\", \"sms\", \"slack\"];\nconst FREQUENCIES: readonly Frequency[] = [\"instant\", \"daily\", \"weekly\", \"off\"];\n\nconst isChannel = (value: unknown): value is Channel => CHANNELS.includes(value as Channel);\nconst isFrequency = (value: unknown): value is Frequency =>\n FREQUENCIES.includes(value as Frequency);\n\nexport type PreferenceRow = {\n userId: string;\n type: string;\n channel: Channel;\n enabled: boolean;\n frequency: Frequency;\n /** Last explicit change. An unsubscribe token issued before it is refused. */\n updatedAt?: Date;\n};\n\nexport type PreferencesOptions = {\n /** What an absent row means. Flip to false for opt-in-only notifications. */\n defaultEnabled?: boolean;\n /** Types that ignore preferences entirely: receipts, security alerts. */\n alwaysSend?: readonly string[];\n unsubscribeTtlSeconds?: number;\n};\n\nconst key = (userId: string, type: string, channel: string) => `${userId} ${type} ${channel}`;\n\ntype PreparedPreferences = Map<string, PreferenceRow>;\n\nexport function buildUnsubscribeToken(\n secret: string,\n userId: string,\n type: string,\n channel: Channel,\n ttlSeconds = DEFAULT_TOKEN_TTL_SECONDS,\n): Promise<string> {\n return signToken(secret, {\n uid: userId,\n purpose: UNSUBSCRIBE_PURPOSE,\n exp: expiresIn(ttlSeconds),\n data: { type, channel },\n });\n}\n\nexport function preferences(options: PreferencesOptions = {}): EasyPingPlugin<\"preferences\"> {\n const defaultEnabled = options.defaultEnabled ?? true;\n const alwaysSend = new Set(options.alwaysSend ?? []);\n\n // Assigned by init(), which easyPing() runs before any hook or route.\n let ctx: PluginInitContext;\n\n const isAllowed = (userId: string, type: string, channel: Channel, rows: PreparedPreferences) => {\n const row = rows.get(key(userId, type, channel));\n return row ? row.enabled && row.frequency !== \"off\" : defaultEnabled;\n };\n\n const load = (userIds: readonly string[]) =>\n ctx.store.find<PreferenceRow>(TABLE, { userId: { in: [...userIds] } });\n\n const save = (row: PreferenceRow) =>\n ctx.store.upsert(TABLE, [{ ...row, updatedAt: new Date() }], {\n onConflict: [\"userId\", \"type\", \"channel\"],\n });\n\n return {\n id: \"preferences\",\n\n init: (context) => {\n ctx = context;\n },\n\n schema: {\n notificationPreference: {\n tableName: TABLE,\n fields: {\n userId: { type: \"string\", required: true },\n type: { type: \"string\", required: true },\n channel: { type: \"string\", required: true },\n enabled: { type: \"boolean\", required: true, default: true },\n frequency: { type: \"string\", required: true, default: \"instant\" },\n updatedAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"userId\", \"type\", \"channel\"],\n },\n },\n\n hooks: {\n /** One query per send; doing this per recipient would be an N+1. */\n prepare: async (context: PrepareContext): Promise<PreparedPreferences> => {\n if (alwaysSend.has(context.type)) return new Map();\n\n const rows = await load(context.recipients.map((recipient) => recipient.userId));\n return new Map(rows.map((row) => [key(row.userId, row.type, row.channel), row]));\n },\n\n resolveChannels: (context: ResolveChannelsContext) => {\n if (alwaysSend.has(context.type)) return context.decisions;\n\n // prepare() failing leaves this undefined. Fail closed rather than\n // assuming everyone opted in: that is exactly how people who\n // unsubscribed get emailed anyway.\n if (!(context.prepared instanceof Map)) {\n return context.decisions.map((decision) => ({ ...decision, action: \"skip\" as const }));\n }\n\n const rows = context.prepared as PreparedPreferences;\n\n return context.decisions.map<ChannelDecision>((decision) =>\n isAllowed(context.recipient.userId, context.type, decision.channel, rows)\n ? decision\n : { ...decision, action: \"skip\" },\n );\n },\n },\n\n routes: [\n {\n path: \"/preferences\",\n method: \"GET\",\n scope: { type: \"user\" },\n handler: async ({ userId }) => {\n const rows = await load([userId ?? \"\"]);\n return Response.json({ preferences: rows, defaultEnabled });\n },\n },\n\n {\n path: \"/preferences\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const parsed = await readJsonBody(request);\n if (\"error\" in parsed) return parsed.error;\n const body = parsed.body;\n\n const bad = (error: string) => Response.json({ error }, { status: 400 });\n\n // Only types the app defined: otherwise every unknown string the\n // client invents is a row that lives forever.\n if (typeof body.type !== \"string\" || !ctx.notificationTypes.includes(body.type)) {\n return bad(\"type must be a configured notification type\");\n }\n if (!isChannel(body.channel)) return bad(`channel must be one of ${CHANNELS.join(\", \")}`);\n if (body.enabled !== undefined && typeof body.enabled !== \"boolean\") {\n return bad(\"enabled must be a boolean\");\n }\n if (body.frequency !== undefined && !isFrequency(body.frequency)) {\n return bad(`frequency must be one of ${FREQUENCIES.join(\", \")}`);\n }\n\n // userId comes from the resolved session, never from the body.\n await save({\n userId: userId ?? \"\",\n type: body.type,\n channel: body.channel,\n enabled: body.enabled ?? true,\n frequency: body.frequency ?? \"instant\",\n });\n\n return Response.json({ ok: true });\n },\n },\n\n {\n // Reached from a mail client with no session, so it is authenticated\n // by the signature on the link itself.\n path: \"/unsubscribe\",\n method: \"POST\",\n scope: { type: \"signed\", purpose: UNSUBSCRIBE_PURPOSE },\n handler: async ({ claims }) => {\n const type = claims?.data?.type;\n const channel = claims?.data?.channel;\n if (!claims || !type || !isChannel(channel)) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n const [current] = await ctx.store.find<PreferenceRow>(\n TABLE,\n { userId: claims.uid, type, channel },\n { limit: 1 },\n );\n\n // Already off: a second click, or a mail client retrying, is fine.\n if (current && !current.enabled && current.frequency === \"off\") {\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n }\n\n // The user changed this preference after the email went out. An old\n // link must not silently undo a newer decision made while logged in.\n if (\n current?.updatedAt &&\n claims.iat !== undefined &&\n current.updatedAt.getTime() > (claims.iat + 1) * 1000\n ) {\n return Response.json({ error: \"invalid token\" }, { status: 400 });\n }\n\n await save({\n userId: claims.uid,\n type,\n channel,\n enabled: false,\n frequency: \"off\",\n });\n\n // Gmail and Yahoo one-click requires the POST itself to unsubscribe,\n // with no confirmation page.\n return Response.json({ ok: true, unsubscribed: { type, channel } });\n },\n },\n ],\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { h as EasyPingPlugin } from '../plugin-
|
|
1
|
+
import { h as EasyPingPlugin } from '../plugin-CiMsGlQe.cjs';
|
|
2
2
|
import { C as Channel, F as Frequency } from '../adapter-BfLe2J0t.cjs';
|
|
3
3
|
|
|
4
4
|
declare const UNSUBSCRIBE_PURPOSE = "unsubscribe";
|
|
@@ -8,6 +8,8 @@ type PreferenceRow = {
|
|
|
8
8
|
channel: Channel;
|
|
9
9
|
enabled: boolean;
|
|
10
10
|
frequency: Frequency;
|
|
11
|
+
/** Last explicit change. An unsubscribe token issued before it is refused. */
|
|
12
|
+
updatedAt?: Date;
|
|
11
13
|
};
|
|
12
14
|
type PreferencesOptions = {
|
|
13
15
|
/** What an absent row means. Flip to false for opt-in-only notifications. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { h as EasyPingPlugin } from '../plugin-
|
|
1
|
+
import { h as EasyPingPlugin } from '../plugin-C9Hoxus2.js';
|
|
2
2
|
import { C as Channel, F as Frequency } from '../adapter-BfLe2J0t.js';
|
|
3
3
|
|
|
4
4
|
declare const UNSUBSCRIBE_PURPOSE = "unsubscribe";
|
|
@@ -8,6 +8,8 @@ type PreferenceRow = {
|
|
|
8
8
|
channel: Channel;
|
|
9
9
|
enabled: boolean;
|
|
10
10
|
frequency: Frequency;
|
|
11
|
+
/** Last explicit change. An unsubscribe token issued before it is refused. */
|
|
12
|
+
updatedAt?: Date;
|
|
11
13
|
};
|
|
12
14
|
type PreferencesOptions = {
|
|
13
15
|
/** What an absent row means. Flip to false for opt-in-only notifications. */
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
import { DEFAULT_TOKEN_TTL_SECONDS, signToken, expiresIn } from '../chunk-
|
|
1
|
+
import { DEFAULT_TOKEN_TTL_SECONDS, signToken, expiresIn, readJsonBody } from '../chunk-DG3ZL5NP.js';
|
|
2
2
|
import '../chunk-PTGHMCCG.js';
|
|
3
3
|
|
|
4
4
|
// src/plugins/preferences/index.ts
|
|
5
5
|
var UNSUBSCRIBE_PURPOSE = "unsubscribe";
|
|
6
6
|
var TABLE = "notification_preference";
|
|
7
|
+
var CHANNELS = ["inApp", "email", "push", "sms", "slack"];
|
|
8
|
+
var FREQUENCIES = ["instant", "daily", "weekly", "off"];
|
|
9
|
+
var isChannel = (value) => CHANNELS.includes(value);
|
|
10
|
+
var isFrequency = (value) => FREQUENCIES.includes(value);
|
|
7
11
|
var key = (userId, type, channel) => `${userId} ${type} ${channel}`;
|
|
8
12
|
function buildUnsubscribeToken(secret, userId, type, channel, ttlSeconds = DEFAULT_TOKEN_TTL_SECONDS) {
|
|
9
13
|
return signToken(secret, {
|
|
@@ -22,7 +26,9 @@ function preferences(options = {}) {
|
|
|
22
26
|
return row ? row.enabled && row.frequency !== "off" : defaultEnabled;
|
|
23
27
|
};
|
|
24
28
|
const load = (userIds) => ctx.store.find(TABLE, { userId: { in: [...userIds] } });
|
|
25
|
-
const save = (row) => ctx.store.upsert(TABLE, [row
|
|
29
|
+
const save = (row) => ctx.store.upsert(TABLE, [{ ...row, updatedAt: /* @__PURE__ */ new Date() }], {
|
|
30
|
+
onConflict: ["userId", "type", "channel"]
|
|
31
|
+
});
|
|
26
32
|
return {
|
|
27
33
|
id: "preferences",
|
|
28
34
|
init: (context) => {
|
|
@@ -36,7 +42,8 @@ function preferences(options = {}) {
|
|
|
36
42
|
type: { type: "string", required: true },
|
|
37
43
|
channel: { type: "string", required: true },
|
|
38
44
|
enabled: { type: "boolean", required: true, default: true },
|
|
39
|
-
frequency: { type: "string", required: true, default: "instant" }
|
|
45
|
+
frequency: { type: "string", required: true, default: "instant" },
|
|
46
|
+
updatedAt: { type: "date", required: true, defaultNow: true }
|
|
40
47
|
},
|
|
41
48
|
primaryKey: ["userId", "type", "channel"]
|
|
42
49
|
}
|
|
@@ -74,9 +81,19 @@ function preferences(options = {}) {
|
|
|
74
81
|
method: "POST",
|
|
75
82
|
scope: { type: "user" },
|
|
76
83
|
handler: async ({ request, userId }) => {
|
|
77
|
-
const
|
|
78
|
-
if (
|
|
79
|
-
|
|
84
|
+
const parsed = await readJsonBody(request);
|
|
85
|
+
if ("error" in parsed) return parsed.error;
|
|
86
|
+
const body = parsed.body;
|
|
87
|
+
const bad = (error) => Response.json({ error }, { status: 400 });
|
|
88
|
+
if (typeof body.type !== "string" || !ctx.notificationTypes.includes(body.type)) {
|
|
89
|
+
return bad("type must be a configured notification type");
|
|
90
|
+
}
|
|
91
|
+
if (!isChannel(body.channel)) return bad(`channel must be one of ${CHANNELS.join(", ")}`);
|
|
92
|
+
if (body.enabled !== void 0 && typeof body.enabled !== "boolean") {
|
|
93
|
+
return bad("enabled must be a boolean");
|
|
94
|
+
}
|
|
95
|
+
if (body.frequency !== void 0 && !isFrequency(body.frequency)) {
|
|
96
|
+
return bad(`frequency must be one of ${FREQUENCIES.join(", ")}`);
|
|
80
97
|
}
|
|
81
98
|
await save({
|
|
82
99
|
userId: userId ?? "",
|
|
@@ -97,7 +114,18 @@ function preferences(options = {}) {
|
|
|
97
114
|
handler: async ({ claims }) => {
|
|
98
115
|
const type = claims?.data?.type;
|
|
99
116
|
const channel = claims?.data?.channel;
|
|
100
|
-
if (!claims || !type || !channel) {
|
|
117
|
+
if (!claims || !type || !isChannel(channel)) {
|
|
118
|
+
return Response.json({ error: "invalid token" }, { status: 400 });
|
|
119
|
+
}
|
|
120
|
+
const [current] = await ctx.store.find(
|
|
121
|
+
TABLE,
|
|
122
|
+
{ userId: claims.uid, type, channel },
|
|
123
|
+
{ limit: 1 }
|
|
124
|
+
);
|
|
125
|
+
if (current && !current.enabled && current.frequency === "off") {
|
|
126
|
+
return Response.json({ ok: true, unsubscribed: { type, channel } });
|
|
127
|
+
}
|
|
128
|
+
if (current?.updatedAt && claims.iat !== void 0 && current.updatedAt.getTime() > (claims.iat + 1) * 1e3) {
|
|
101
129
|
return Response.json({ error: "invalid token" }, { status: 400 });
|
|
102
130
|
}
|
|
103
131
|
await save({
|