@appgrowstack/app-events 0.7.0 → 0.8.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/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  アプリへの入れ方は `README.md` の「入れる」。0.5.0 までは app-playbook の `packages/app-events` で作り、アプリの api にコピーして配っていた。
4
4
 
5
+ ## 0.8.0(2026-11-24)
6
+
7
+ ### RevenueCat の webhook の受け口を足した
8
+
9
+ - `receiveRevenueCatWebhook({ project, growth, secret }, authorization, body)` を足した。Authorization を確かめ、本文を `subscription` で appgrowstack に渡し、RevenueCat に送り直させるか(200・401・503)を決める。前はアプリごとに同じ関数を持っていた(app-growth の `docs/security.md` 4.8節・SC11)
10
+ - `isRevenueCatAuthorized(header, secret)` は、両方の sha256 を全部の byte で比べる(かかる時間は値の中身にも長さにもよらない)。違う値・長さの違う値・空・秘密が無いは false。async になった
11
+ - `permanentRpcErrorCode(error)` も出した
12
+
13
+ アプリの側で要ること:自前の `isRevenueCatAuthorized`・`receiveRevenueCatWebhook` を消し、この関数を呼ぶ(`growth` に `env.APPGROWSTACK`、`secret` に `env.REVENUECAT_WEBHOOK_AUTH`)
14
+
15
+ ### 本文を流れのまま数える
16
+
17
+ - `receiveAppEvents` は本文を全部読んでから大きさを見ていた。流れのまま数え、`maxBytes` を超えたところで読むのをやめて 413 にする(`content-length` の無い・偽った本文でも全部をメモリに読まない)。`readCapped` も出した
18
+
19
+ アプリの側で要ること:無い
20
+
5
21
  ## 0.7.0(2026-11-23)
6
22
 
7
23
  ### 共通カタログの元を app-sdk に移した
package/README.md CHANGED
@@ -225,6 +225,24 @@ app.post("/v1/events", authenticate(auth), appEventsHandler({
225
225
  - 外した理由はログと応答に出るので、長い名前と値そのものは載せない
226
226
  - ごほうび習慣の前の受け口(`readEnvelope`)の `MAX_PROPERTIES`・`MAX_TEXT` と同じ数え方(引数の数・名前の長さ・文字列の値の長さ)。数と真偽の値は長さを数えない
227
227
 
228
+ ## RevenueCatのwebhookを受ける
229
+
230
+ アプリのWorkerがRevenueCatのwebhookを受け、`subscription`でappgrowstackに渡す(app-growthはRevenueCatのキーを持たない)。
231
+
232
+ ```ts
233
+ import { receiveRevenueCatWebhook } from "@appgrowstack/app-events"
234
+
235
+ // パスはアプリが決める
236
+ app.post(REVENUECAT_WEBHOOK_PATH, async (c) => {
237
+ const body = await c.req.json().catch(() => null)
238
+ const r = await receiveRevenueCatWebhook({ project: "reading-memory", growth: c.env.APPGROWSTACK, secret: c.env.REVENUECAT_WEBHOOK_AUTH }, c.req.header("Authorization"), body)
239
+ return c.json(r.body, r.status)
240
+ })
241
+ ```
242
+
243
+ - Authorizationは両方のsha256を全部のbyteで比べる(時間が値の中身にも長さにもよらない)。違う・長さの違う・空・秘密が無いは401
244
+ - 読めない本文・匿名だけの人・送り直しても通らない誤りは200(送り直させない)。bindingが無い・一時的な誤りは503(RevenueCatが送り直す。`subscription`はidで冪等)
245
+
228
246
  ## 確かめる
229
247
 
230
248
  ```sh
package/dist/handler.d.ts CHANGED
@@ -83,6 +83,10 @@ export interface RequestContext {
83
83
  */
84
84
  userId?: string;
85
85
  }
86
+ /**
87
+ * 本文を流れのまま読み、max バイトを超えたら読むのをやめて null を返す(残りは cancel する)。本文が無ければ空
88
+ */
89
+ export declare function readCapped(body: ReadableStream<Uint8Array> | null, max: number): Promise<Uint8Array | null>;
86
90
  export declare function receiveAppEvents<E>(req: Request, env: E, waitUntil: (p: Promise<unknown>) => void, opts: AppEventsOptions<E>, request?: RequestContext): Promise<Response>;
87
91
  /** Hono の Context のうち、使う所だけ */
88
92
  export interface HonoLikeContext<E> {
package/dist/handler.js CHANGED
@@ -2,16 +2,45 @@ import { COMMON_CATALOG } from "./common-catalog.generated.js";
2
2
  import { parseEnvelope } from "./envelope.js";
3
3
  import { eventsTable, hourlyBudget, isInternalInstall, writeEvents } from "./store.js";
4
4
  const json = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json; charset=utf-8" } });
5
+ /**
6
+ * 本文を流れのまま読み、max バイトを超えたら読むのをやめて null を返す(残りは cancel する)。本文が無ければ空
7
+ */
8
+ export async function readCapped(body, max) {
9
+ if (!body)
10
+ return new Uint8Array(0);
11
+ const reader = body.getReader();
12
+ const chunks = [];
13
+ let total = 0;
14
+ for (;;) {
15
+ const { done, value } = await reader.read();
16
+ if (done)
17
+ break;
18
+ total += value.byteLength;
19
+ if (total > max) {
20
+ await reader.cancel().catch(() => { });
21
+ return null;
22
+ }
23
+ chunks.push(value);
24
+ }
25
+ const out = new Uint8Array(total);
26
+ let at = 0;
27
+ for (const c of chunks) {
28
+ out.set(c, at);
29
+ at += c.byteLength;
30
+ }
31
+ return out;
32
+ }
5
33
  export async function receiveAppEvents(req, env, waitUntil, opts, request = {}) {
6
34
  const now = opts.now?.() ?? Date.now();
7
35
  const maxBytes = opts.maxBytes ?? 256 * 1024;
8
36
  const verifiedUid = opts.uid ? await opts.uid(req, env) : request.userId;
9
- // 申告の長さで先に断る(読んでから数えるだけでは、大きな本文を全部読んでしまう)
37
+ // 申告の長さで先に断る。申告の無い・偽った本文も、流れのまま数えて上限を超えたところで止める(全部をメモリに読まない)
10
38
  if (Number(req.headers.get("content-length") ?? "0") > maxBytes)
11
39
  return json({ error: `本文が ${maxBytes} バイトを超えている` }, 413);
12
- const text = await req.text();
13
- if (new TextEncoder().encode(text).byteLength > maxBytes)
40
+ const bytes = await readCapped(req.body, maxBytes);
41
+ if (bytes === null)
14
42
  return json({ error: `本文が ${maxBytes} バイトを超えている` }, 413);
43
+ const text = new TextDecoder().decode(bytes);
15
44
  let body;
16
45
  try {
17
46
  body = JSON.parse(text);
package/dist/index.d.ts CHANGED
@@ -3,5 +3,6 @@ export { COMMON_CATALOG, COMMON_CATALOG_SOURCE, COMMON_EVENT_NAMES, type CommonE
3
3
  export * from "./envelope.js";
4
4
  export * from "./forward.js";
5
5
  export * from "./handler.js";
6
+ export * from "./revenuecat.js";
6
7
  export * from "./store.js";
7
8
  export { APP_EVENTS_MIGRATION } from "./migration.js";
package/dist/index.js CHANGED
@@ -4,5 +4,6 @@ export { COMMON_CATALOG, COMMON_CATALOG_SOURCE, COMMON_EVENT_NAMES } from "./com
4
4
  export * from "./envelope.js";
5
5
  export * from "./forward.js";
6
6
  export * from "./handler.js";
7
+ export * from "./revenuecat.js";
7
8
  export * from "./store.js";
8
9
  export { APP_EVENTS_MIGRATION } from "./migration.js";
@@ -0,0 +1,39 @@
1
+ import { type AppGrowStackService } from "@appgrowstack/app-contract";
2
+ /**
3
+ * RevenueCat の webhook の Authorization(RevenueCat の画面で決めた値をそのまま送ってくる。頭の Bearer は外して比べる)を秘密と比べる。
4
+ * 両方の sha256 を全部の byte で比べるので、かかる時間は値の中身にも長さにもよらない。秘密・頭のどちらかが無い・空なら false
5
+ */
6
+ export declare function isRevenueCatAuthorized(header: string | null | undefined, secret: string | null | undefined): Promise<boolean>;
7
+ export type RevenueCatResult = {
8
+ status: 200;
9
+ body: {
10
+ ok: true;
11
+ recorded: boolean;
12
+ };
13
+ } | {
14
+ status: 401 | 503;
15
+ body: {
16
+ error: {
17
+ code: string;
18
+ message: string;
19
+ };
20
+ };
21
+ };
22
+ /** appgrowstack の誤りの code(Service Binding を越えると name は Error になるので、message の頭の [input] などで読む)。送り直しても通らない物なら返す */
23
+ export declare function permanentRpcErrorCode(error: unknown): string | null;
24
+ export interface RevenueCatWebhookOptions {
25
+ /** appgrowstack のプロジェクトの id(wrangler.jsonc の services の props.project と同じ) */
26
+ project: string;
27
+ /** Service Binding。無い環境(ローカル・まだ出していない Worker)は null か undefined */
28
+ growth: Pick<AppGrowStackService, "subscription"> | null | undefined;
29
+ /** RevenueCat の画面で決めた Authorization の値(wrangler secret) */
30
+ secret: string | null | undefined;
31
+ }
32
+ /**
33
+ * RevenueCat の webhook の1件を subscription で渡す。
34
+ * - Authorization が違う・長さが違う・空・秘密が無いは 401(ほかは何もしない)
35
+ * - 読めない本文・匿名だけの人・送り直しても通らない誤り(PERMANENT_RPC_ERRORS)は 200(RevenueCat に送り直させない)。
36
+ * 入力の誤りは warn、設定の誤り(project・forbidden など)は error でログに残す(id と code だけ。本文は書かない)
37
+ * - binding が無い・appgrowstack が落ちている・一時的な誤りは 503(RevenueCat が後で送り直す。subscription は id で冪等なので重ならない)
38
+ */
39
+ export declare function receiveRevenueCatWebhook(opts: RevenueCatWebhookOptions, authorization: string | null | undefined, body: unknown): Promise<RevenueCatResult>;
@@ -0,0 +1,65 @@
1
+ // RevenueCat の webhook の受け口(docs/security.md 4.8節・SC11)。アプリの Worker が受け、appgrowstack の subscription で渡す(app-growth は RevenueCat の鍵を持たない)。
2
+ // 前は製品ごとに同じ関数を持っていた。Authorization の比べ方(一定時間・長さを漏らさない)と、RevenueCat に送り直させるかの決め方をここで1つにする
3
+ import { RPC_ERROR_CODES, rpcErrorCode, rpcErrorMessage, subscriptionInputOf } from "@appgrowstack/app-contract";
4
+ const sha256 = async (text) => new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
5
+ /**
6
+ * RevenueCat の webhook の Authorization(RevenueCat の画面で決めた値をそのまま送ってくる。頭の Bearer は外して比べる)を秘密と比べる。
7
+ * 両方の sha256 を全部の byte で比べるので、かかる時間は値の中身にも長さにもよらない。秘密・頭のどちらかが無い・空なら false
8
+ */
9
+ export async function isRevenueCatAuthorized(header, secret) {
10
+ const given = (header ?? "").replace(/^Bearer\s+/i, "");
11
+ const [a, b] = await Promise.all([sha256(given), sha256(secret ?? "")]);
12
+ let diff = 0;
13
+ for (let i = 0; i < a.byteLength; i += 1)
14
+ diff |= (a[i] ?? 0) ^ (b[i] ?? 0);
15
+ // 空の秘密・空の頭は、比べた結果に関わらず通さない(比べる処理は同じだけ回す)
16
+ return diff === 0 && given !== "" && (secret ?? "") !== "";
17
+ }
18
+ /**
19
+ * 送り直しても通らない誤り(入力の形・知らないプロジェクトか機能が off・props の食い違い・知らない物・今の状態ではできない・まだ作っていない)。
20
+ * ほか(retry_later・rate_limited・code の無い通信の失敗)は一時的とみる
21
+ */
22
+ const PERMANENT_RPC_ERRORS = new Set([
23
+ RPC_ERROR_CODES.input,
24
+ RPC_ERROR_CODES.project,
25
+ RPC_ERROR_CODES.forbidden,
26
+ RPC_ERROR_CODES.notFound,
27
+ RPC_ERROR_CODES.conflict,
28
+ RPC_ERROR_CODES.notImplemented,
29
+ ]);
30
+ /** appgrowstack の誤りの code(Service Binding を越えると name は Error になるので、message の頭の [input] などで読む)。送り直しても通らない物なら返す */
31
+ export function permanentRpcErrorCode(error) {
32
+ const code = rpcErrorCode(error);
33
+ return code !== null && PERMANENT_RPC_ERRORS.has(code) ? code : null;
34
+ }
35
+ /**
36
+ * RevenueCat の webhook の1件を subscription で渡す。
37
+ * - Authorization が違う・長さが違う・空・秘密が無いは 401(ほかは何もしない)
38
+ * - 読めない本文・匿名だけの人・送り直しても通らない誤り(PERMANENT_RPC_ERRORS)は 200(RevenueCat に送り直させない)。
39
+ * 入力の誤りは warn、設定の誤り(project・forbidden など)は error でログに残す(id と code だけ。本文は書かない)
40
+ * - binding が無い・appgrowstack が落ちている・一時的な誤りは 503(RevenueCat が後で送り直す。subscription は id で冪等なので重ならない)
41
+ */
42
+ export async function receiveRevenueCatWebhook(opts, authorization, body) {
43
+ if (!(await isRevenueCatAuthorized(authorization, opts.secret))) {
44
+ return { status: 401, body: { error: { code: "unauthorized", message: "Authorization が違う" } } };
45
+ }
46
+ if (!opts.growth)
47
+ return { status: 503, body: { error: { code: "not_configured", message: "APPGROWSTACK が無い" } } };
48
+ const input = subscriptionInputOf(opts.project, body);
49
+ if (!input)
50
+ return { status: 200, body: { ok: true, recorded: false } };
51
+ try {
52
+ await opts.growth.subscription(input);
53
+ }
54
+ catch (error) {
55
+ const code = permanentRpcErrorCode(error);
56
+ if (code !== null) {
57
+ const log = code === RPC_ERROR_CODES.input ? console.warn : console.error;
58
+ log(JSON.stringify({ msg: "appgrowstack: subscription を受けてもらえない(送り直さない)", id: input.id, code, error: rpcErrorMessage(error).slice(0, 300) }));
59
+ return { status: 200, body: { ok: true, recorded: false } };
60
+ }
61
+ console.error(JSON.stringify({ msg: "appgrowstack: subscription に失敗", id: input.id, error: String(error).slice(0, 300) }));
62
+ return { status: 503, body: { error: { code: "unavailable", message: "appgrowstack に渡せなかった" } } };
63
+ }
64
+ return { status: 200, body: { ok: true, recorded: true } };
65
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@appgrowstack/app-events",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "アプリの Worker が出来事の封筒を受け、確かめ、D1 の app_events に書き、決めた出来事を転送先(appgrowstack の track・webhook)へ渡す",
6
6
  "license": "MIT",