@appgrowstack/app-contract 0.0.0-stage → 0.1.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/dist/rpc.js ADDED
@@ -0,0 +1,111 @@
1
+ export const APPGROWSTACK_BINDING = "APPGROWSTACK";
2
+ export const APPGROWSTACK_SERVICE = "appgrowstack-core";
3
+ export const APPGROWSTACK_ENTRYPOINT = "AppGrowStackRpc";
4
+ /** RPC の名前と、入力と答えの schema(schema/ からの相対の道と $defs の名前)。core はこれで受けた値を確かめる */
5
+ export const rpcSchemas = {
6
+ track: { input: ["people/track.schema.json"], result: ["people/track.schema.json", "result"] },
7
+ identify: { input: ["people/identify.schema.json"], result: ["people/identify.schema.json", "result"] },
8
+ forget: { input: ["people/forget.schema.json"], result: null },
9
+ subscription: { input: ["people/subscription.schema.json"], result: null },
10
+ touch: { input: ["people/touch.schema.json"], result: ["people/touch.schema.json", "result"] },
11
+ send: { input: ["notify/send.schema.json"], result: ["notify/send.schema.json", "result"] },
12
+ registerDevice: { input: ["notify/device.schema.json"], result: null },
13
+ unregisterDevice: { input: ["notify/device.schema.json", "unregister"], result: null },
14
+ registerWidgetPush: { input: ["notify/device.schema.json", "registerWidgetPush"], result: null },
15
+ unregisterWidgetPush: { input: ["notify/device.schema.json", "unregisterWidgetPush"], result: null },
16
+ refreshWidgets: { input: ["notify/device.schema.json", "refreshWidgets"], result: ["notify/device.schema.json", "refreshWidgetsResult"] },
17
+ createLink: { input: ["links/link.schema.json", "createInput"], result: ["links/link.schema.json"] },
18
+ createInvite: { input: ["links/link.schema.json", "inviteInput"], result: ["links/link.schema.json"] },
19
+ recordAttribution: { input: ["links/attribution.schema.json", "recordInput"], result: ["links/attribution.schema.json", "response"] },
20
+ createTicket: { input: ["support/ticket.schema.json", "createInput"], result: ["support/ticket.schema.json", "createResponse"] },
21
+ };
22
+ /**
23
+ * Worker の間の RPC(アプリの APPGROWSTACK・api の CORE・core の NOTIFY と NOTIFY_ADMIN)が投げる誤りの code。
24
+ * Service Binding は Error の name を運ばない("Error" になり、message の頭に元の name が付く)ので、name では見分けない。
25
+ * 投げる側は AppGrowStackRpcError(message の頭に「[<code>] 」を書く)、受ける側は rpcErrorCode(error) で code を読む
26
+ */
27
+ export const RPC_ERROR_CODES = {
28
+ /** 入力が schema に合わない */
29
+ input: "input",
30
+ /** 知らないプロジェクト・その機能が off */
31
+ project: "project",
32
+ /** 外(Apple の AdServices など)がまだ答えない。何も残していないので、後で同じ物を送り直す */
33
+ retryLater: "retry_later",
34
+ /** 回数の上限(問い合わせは install_id ごとに1時間に5件・添付は1件に4枚) */
35
+ rateLimited: "rate_limited",
36
+ /** binding の props の project と入力の project が違う・props が無い(AC-7) */
37
+ forbidden: "forbidden",
38
+ /** 知らない物(notify の施策・案・問い合わせ)。管理の道は 404 にする */
39
+ notFound: "not_found",
40
+ /** 今の状態ではできない(proposed でない案の承認・解決にした問い合わせへの返事)。管理の道は 409 にする */
41
+ conflict: "conflict",
42
+ /** 約束にはあるがまだ作っていない(型だけ通すスタブ・AGENTS.md)。api と管理の道は 501 にし、core_error として数えない */
43
+ notImplemented: "not_implemented",
44
+ /** 撮影の組のファイルが、組を作った時の sha256・寸法と合わない(R12)。管理の道は 409 capture_mismatch にする。message の2行目からは1行に1つ「<locale>/<device>/<screen>/<kind>: <理由>」 */
45
+ captureMismatch: "capture_mismatch",
46
+ /** 参考の素材の URL を読めない・ログインが要る(R12)。管理の道は 422 fetch_failed にする */
47
+ fetchFailed: "fetch_failed",
48
+ /** 参考の素材のファイルが sha256 と合わない・R2 に無い(R12)。管理の道は 409 reference_mismatch にする */
49
+ referenceMismatch: "reference_mismatch",
50
+ /** Web のページを撮る Browser Run のキーが無い・断られた(R12)。管理の道は 501 browser_unavailable にする */
51
+ browserUnavailable: "browser_unavailable",
52
+ /** R13 の SQL が決まりに合わない(1つの SELECT でない・day の条件が無い・400日を超える・person_key を返す)。管理の道は 400 sql_refused にする */
53
+ sqlRefused: "sql_refused",
54
+ /** R13 の1回か1日のスキャンの上限を超えた。管理の道は 429 scan_limit にする */
55
+ scanLimit: "scan_limit",
56
+ };
57
+ const RPC_ERROR_CODE_SET = new Set(Object.values(RPC_ERROR_CODES));
58
+ const RPC_ERROR_HEAD = /^\[([a-z_]+)\] /;
59
+ /**
60
+ * RPC で投げる誤り。message は「[<code>] <中身>」。name は既定の "Error" のまま(name を変えると workerd が message の頭に足す)。
61
+ * 同じ Worker の中では code の欄でも読めるが、Service Binding を越えると欄は運ばれないことがあるので、読むのはいつも rpcErrorCode
62
+ */
63
+ export class AppGrowStackRpcError extends Error {
64
+ code;
65
+ constructor(code, message) {
66
+ super(`[${code}] ${message}`);
67
+ this.code = code;
68
+ }
69
+ }
70
+ /** 約束にはあるがまだ作っていない物のスタブが投げる誤り(code not_implemented) */
71
+ export function notImplemented(what) {
72
+ return new AppGrowStackRpcError(RPC_ERROR_CODES.notImplemented, `${what} はまだ無い`);
73
+ }
74
+ /** 受けた誤りの code。AppGrowStackRpcError でない誤り(通信の失敗・中の誤り)は null */
75
+ export function rpcErrorCode(error) {
76
+ const message = error?.message;
77
+ if (typeof message !== "string")
78
+ return null;
79
+ const head = RPC_ERROR_HEAD.exec(message);
80
+ return head && RPC_ERROR_CODE_SET.has(head[1]) ? head[1] : null;
81
+ }
82
+ /** 受けた誤りの中身(頭の「[<code>] 」を外した物)。人に見せる誤りの文に使う */
83
+ export function rpcErrorMessage(error) {
84
+ const message = error?.message;
85
+ if (typeof message !== "string")
86
+ return String(error);
87
+ return rpcErrorCode(error) === null ? message : message.replace(RPC_ERROR_HEAD, "");
88
+ }
89
+ // --- appgrowstack-api → appgrowstack-core ------------------------------------
90
+ export const APPGROWSTACK_API_ENTRYPOINT = "AppGrowStackApiRpc";
91
+ /** api の SESSION_LIVE の Durable Object の binding(script_name: appgrowstack-core・class SessionLive)。idFromName("<project>:<install_id>") */
92
+ export const SESSION_LIVE_BINDING = "SESSION_LIVE";
93
+ export const SESSION_LIVE_CLASS = "SessionLive";
94
+ // --- appgrowstack-core → appgrowstack-notify(アプリからは呼ばない) --------------
95
+ export const NOTIFY_BINDING = "NOTIFY";
96
+ export const NOTIFY_SERVICE = "appgrowstack-notify";
97
+ export const NOTIFY_ENTRYPOINT = "NotifyRpc";
98
+ // --- appgrowstack-core → appgrowstack-notify の管理(/v1/notify/* の中身) ---------
99
+ export const NOTIFY_ADMIN_BINDING = "NOTIFY_ADMIN";
100
+ export const NOTIFY_ADMIN_ENTRYPOINT = "NotifyAdminRpc";
101
+ // --- appgrowstack-core → appgrowstack-creative の管理(/v1/creatives/* の中身) ---------
102
+ export const CREATIVE_ADMIN_BINDING = "CREATIVE_ADMIN";
103
+ export const CREATIVE_SERVICE = "appgrowstack-creative";
104
+ export const CREATIVE_ADMIN_ENTRYPOINT = "CreativeAdminRpc";
105
+ // --- core・notify・creative → appgrowstack-insights(仮説の記録と person_key) ------------
106
+ export const INSIGHTS_BINDING = "INSIGHTS";
107
+ export const INSIGHTS_SERVICE = "appgrowstack-insights";
108
+ export const INSIGHTS_ENTRYPOINT = "InsightsRpc";
109
+ // --- appgrowstack-core → appgrowstack-insights の管理(/v1/insights/*・/v1/ledger/* の中身) ---------
110
+ export const INSIGHTS_ADMIN_BINDING = "INSIGHTS_ADMIN";
111
+ export const INSIGHTS_ADMIN_ENTRYPOINT = "InsightsAdminRpc";
@@ -0,0 +1,34 @@
1
+ /** 塊の PUT とライブの頭。端末の install_id(小文字にしてから比べる)。upload_token と live の token の HMAC と、DO の名前に使う */
2
+ export declare const SESSION_INSTALL_HEADER = "X-Session-Install";
3
+ /** 塊の PUT の頭。始まりのバッチの答えの upload_token */
4
+ export declare const SESSION_UPLOAD_HEADER = "X-Session-Upload";
5
+ /** api が core の DO SessionLive に渡す頭。公開キーから引いたプロジェクト(公開キーそのものは渡さない) */
6
+ export declare const SESSION_LIVE_PROJECT_HEADER = "X-AppGrowStack-Project";
7
+ /** api と core の Worker の secret の名前(同じ値) */
8
+ export declare const SESSION_TOKEN_SECRET = "SESSION_TOKEN_SECRET";
9
+ /** upload_token: <until(Unix 秒・10桁)>.<HMAC の hex 64文字>(live の token と同じ形)。until はセッションの始まり+8日 */
10
+ export declare const SESSION_UPLOAD_TOKEN_PATTERN: RegExp;
11
+ /** live の token: <until(Unix 秒・10桁)>.<HMAC の hex 64文字>。until は見る人の sessions_live_watch.until */
12
+ export declare const SESSION_LIVE_TOKEN_PATTERN: RegExp;
13
+ /**
14
+ * upload_token の寿命。セッションの始まりから8日(端末は塊を7日まで溜める。core は8日より前に始まったセッションを受けない)。
15
+ * 一度見えた token で、そのセッションに塊をいつまでも置けないようにする(docs/security.md 4.15節)
16
+ */
17
+ export declare const SESSION_UPLOAD_TTL_MS: number;
18
+ /** live の token の until の先の上限。見る人の待ちは30分なので、それより先の until は作らない(時計のずれに1分を見る) */
19
+ export declare const SESSION_LIVE_MAX_AHEAD_MS: number;
20
+ /** upload_token の HMAC の中身。until は Unix 秒 */
21
+ export declare function sessionUploadMessage(project: string, session_id: string, install_id: string, until: number): string;
22
+ /** live の token の HMAC の中身。until は Unix 秒 */
23
+ export declare function sessionLiveMessage(project: string, install_id: string, until: number): string;
24
+ /** core が始まりのバッチの答えに入れる upload_token。until は Unix 秒(セッションの始まり+SESSION_UPLOAD_TTL_MS) */
25
+ export declare function signSessionUploadToken(secret: string, project: string, session_id: string, install_id: string, until: number): Promise<string>;
26
+ /** api が塊の PUT で確かめる。形が違う・until を過ぎた・until が今から寿命より先・HMAC が合わなければ false(比べるのは crypto.subtle.verify で、時間で漏らさない) */
27
+ export declare function verifySessionUploadToken(secret: string, token: string, project: string, session_id: string, install_id: string, nowMs: number): Promise<boolean>;
28
+ /** core がバッチの答えの live に入れる token。until は Unix 秒 */
29
+ export declare function signSessionLiveToken(secret: string, project: string, install_id: string, until: number): Promise<string>;
30
+ /**
31
+ * api がライブの WebSocket を開く前に確かめる。形が違う・until を過ぎた・until が31分より先・HMAC が合わなければ false。
32
+ * 見る人がまだつないでいるかは core の DO が確かめる
33
+ */
34
+ export declare function verifySessionLiveToken(secret: string, token: string, project: string, install_id: string, nowMs: number): Promise<boolean>;
@@ -0,0 +1,78 @@
1
+ // R8 行動の記録の端末の道の頭と token(docs/sessions.md 6.1節)。api と core が同じ物を使う。
2
+ // upload_token と live の token は、どちらも SESSION_TOKEN_SECRET の HMAC-SHA256。用途の頭(upload: と live:)で分けるので、片方をもう片方に使えない
3
+ /** 塊の PUT とライブの頭。端末の install_id(小文字にしてから比べる)。upload_token と live の token の HMAC と、DO の名前に使う */
4
+ export const SESSION_INSTALL_HEADER = "X-Session-Install";
5
+ /** 塊の PUT の頭。始まりのバッチの答えの upload_token */
6
+ export const SESSION_UPLOAD_HEADER = "X-Session-Upload";
7
+ /** api が core の DO SessionLive に渡す頭。公開キーから引いたプロジェクト(公開キーそのものは渡さない) */
8
+ export const SESSION_LIVE_PROJECT_HEADER = "X-AppGrowStack-Project";
9
+ /** api と core の Worker の secret の名前(同じ値) */
10
+ export const SESSION_TOKEN_SECRET = "SESSION_TOKEN_SECRET";
11
+ /** upload_token: <until(Unix 秒・10桁)>.<HMAC の hex 64文字>(live の token と同じ形)。until はセッションの始まり+8日 */
12
+ export const SESSION_UPLOAD_TOKEN_PATTERN = /^[0-9]{10}\.[0-9a-f]{64}$/;
13
+ /** live の token: <until(Unix 秒・10桁)>.<HMAC の hex 64文字>。until は見る人の sessions_live_watch.until */
14
+ export const SESSION_LIVE_TOKEN_PATTERN = /^[0-9]{10}\.[0-9a-f]{64}$/;
15
+ /**
16
+ * upload_token の寿命。セッションの始まりから8日(端末は塊を7日まで溜める。core は8日より前に始まったセッションを受けない)。
17
+ * 一度見えた token で、そのセッションに塊をいつまでも置けないようにする(docs/security.md 4.15節)
18
+ */
19
+ export const SESSION_UPLOAD_TTL_MS = 8 * 24 * 60 * 60 * 1000;
20
+ /** live の token の until の先の上限。見る人の待ちは30分なので、それより先の until は作らない(時計のずれに1分を見る) */
21
+ export const SESSION_LIVE_MAX_AHEAD_MS = 31 * 60 * 1000;
22
+ /** upload_token の HMAC の中身。until は Unix 秒 */
23
+ export function sessionUploadMessage(project, session_id, install_id, until) {
24
+ return `upload:${project}:${session_id}:${install_id.toLowerCase()}:${until}`;
25
+ }
26
+ /** live の token の HMAC の中身。until は Unix 秒 */
27
+ export function sessionLiveMessage(project, install_id, until) {
28
+ return `live:${project}:${install_id.toLowerCase()}:${until}`;
29
+ }
30
+ async function hmacKey(secret, usage) {
31
+ return crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [usage]);
32
+ }
33
+ function hex(bytes) {
34
+ return [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
35
+ }
36
+ function unhex(value) {
37
+ const out = new Uint8Array(new ArrayBuffer(value.length / 2));
38
+ for (let i = 0; i < out.length; i++)
39
+ out[i] = parseInt(value.slice(i * 2, i * 2 + 2), 16);
40
+ return out;
41
+ }
42
+ async function sign(secret, message) {
43
+ return hex(await crypto.subtle.sign("HMAC", await hmacKey(secret, "sign"), new TextEncoder().encode(message)));
44
+ }
45
+ async function verify(secret, message, signatureHex) {
46
+ return crypto.subtle.verify("HMAC", await hmacKey(secret, "verify"), unhex(signatureHex), new TextEncoder().encode(message));
47
+ }
48
+ /** core が始まりのバッチの答えに入れる upload_token。until は Unix 秒(セッションの始まり+SESSION_UPLOAD_TTL_MS) */
49
+ export async function signSessionUploadToken(secret, project, session_id, install_id, until) {
50
+ return `${until}.${await sign(secret, sessionUploadMessage(project, session_id, install_id, until))}`;
51
+ }
52
+ /** api が塊の PUT で確かめる。形が違う・until を過ぎた・until が今から寿命より先・HMAC が合わなければ false(比べるのは crypto.subtle.verify で、時間で漏らさない) */
53
+ export async function verifySessionUploadToken(secret, token, project, session_id, install_id, nowMs) {
54
+ if (!SESSION_UPLOAD_TOKEN_PATTERN.test(token))
55
+ return false;
56
+ const [untilText, signature] = token.split(".");
57
+ const until = Number(untilText);
58
+ if (until * 1000 <= nowMs || until * 1000 > nowMs + SESSION_UPLOAD_TTL_MS + 10 * 60 * 1000)
59
+ return false;
60
+ return verify(secret, sessionUploadMessage(project, session_id, install_id, until), signature);
61
+ }
62
+ /** core がバッチの答えの live に入れる token。until は Unix 秒 */
63
+ export async function signSessionLiveToken(secret, project, install_id, until) {
64
+ return `${until}.${await sign(secret, sessionLiveMessage(project, install_id, until))}`;
65
+ }
66
+ /**
67
+ * api がライブの WebSocket を開く前に確かめる。形が違う・until を過ぎた・until が31分より先・HMAC が合わなければ false。
68
+ * 見る人がまだつないでいるかは core の DO が確かめる
69
+ */
70
+ export async function verifySessionLiveToken(secret, token, project, install_id, nowMs) {
71
+ if (!SESSION_LIVE_TOKEN_PATTERN.test(token))
72
+ return false;
73
+ const [untilText, signature] = token.split(".");
74
+ const until = Number(untilText);
75
+ if (until * 1000 <= nowMs || until * 1000 > nowMs + SESSION_LIVE_MAX_AHEAD_MS)
76
+ return false;
77
+ return verify(secret, sessionLiveMessage(project, install_id, until), signature);
78
+ }
@@ -0,0 +1,28 @@
1
+ import type { TouchBudget, TouchChannel, TouchUsed } from "./generated/schema.js";
2
+ export interface TouchRecord {
3
+ at: number;
4
+ channel: TouchChannel;
5
+ }
6
+ /** その人の時間帯の日付(YYYY-MM-DD) */
7
+ export declare function touchDay(at: number, timeZone: string): string;
8
+ /** その日を含む週の月曜の日付 */
9
+ export declare function touchWeek(day: string): string;
10
+ /** now の日と週に、その人に触れた数。channel_day はその経路の今日の数 */
11
+ export declare function touchUsage(records: readonly TouchRecord[], input: {
12
+ now: number;
13
+ timeZone: string;
14
+ channel: TouchChannel;
15
+ }): TouchUsed & {
16
+ day_key: string;
17
+ week_key: string;
18
+ };
19
+ /** 今日あと何回触れてよいか(全部の経路と、この経路の小さい方)。上限が無ければ null */
20
+ export declare function touchRemaining(budget: Pick<TouchBudget, "max_per_day" | "max_per_week" | "channels"> | null, used: TouchUsed, channel: TouchChannel): number | null;
21
+ /** registry_touch_budget の行から TouchBudget の上限の部分 */
22
+ export declare function touchBudgetOf(row: {
23
+ max_per_day: number;
24
+ max_per_week: number;
25
+ inapp_per_day: number | null;
26
+ push_per_day: number | null;
27
+ email_per_day: number | null;
28
+ }): Pick<TouchBudget, "max_per_day" | "max_per_week" | "channels">;
package/dist/touch.js ADDED
@@ -0,0 +1,49 @@
1
+ /** その人の時間帯の日付(YYYY-MM-DD) */
2
+ export function touchDay(at, timeZone) {
3
+ const parts = new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).formatToParts(new Date(at));
4
+ const v = (t) => parts.find((p) => p.type === t).value;
5
+ return `${v("year")}-${v("month")}-${v("day")}`;
6
+ }
7
+ /** その日を含む週の月曜の日付 */
8
+ export function touchWeek(day) {
9
+ const d = new Date(`${day}T00:00:00Z`);
10
+ const back = (d.getUTCDay() + 6) % 7;
11
+ return new Date(d.getTime() - back * 86_400_000).toISOString().slice(0, 10);
12
+ }
13
+ /** now の日と週に、その人に触れた数。channel_day はその経路の今日の数 */
14
+ export function touchUsage(records, input) {
15
+ const day = touchDay(input.now, input.timeZone);
16
+ const week = touchWeek(day);
17
+ let d = 0;
18
+ let w = 0;
19
+ let c = 0;
20
+ for (const r of records) {
21
+ const rd = touchDay(r.at, input.timeZone);
22
+ if (touchWeek(rd) === week)
23
+ w++;
24
+ if (rd === day) {
25
+ d++;
26
+ if (r.channel === input.channel)
27
+ c++;
28
+ }
29
+ }
30
+ return { day: d, week: w, channel_day: c, day_key: day, week_key: week };
31
+ }
32
+ /** 今日あと何回触れてよいか(全部の経路と、この経路の小さい方)。上限が無ければ null */
33
+ export function touchRemaining(budget, used, channel) {
34
+ if (budget === null)
35
+ return null;
36
+ const channelCap = budget.channels[channel];
37
+ return Math.max(0, Math.min(budget.max_per_day - used.day, budget.max_per_week - used.week, channelCap === undefined ? Number.POSITIVE_INFINITY : channelCap - used.channel_day));
38
+ }
39
+ /** registry_touch_budget の行から TouchBudget の上限の部分 */
40
+ export function touchBudgetOf(row) {
41
+ const channels = {};
42
+ if (row.inapp_per_day !== null)
43
+ channels.inapp = row.inapp_per_day;
44
+ if (row.push_per_day !== null)
45
+ channels.push = row.push_per_day;
46
+ if (row.email_per_day !== null)
47
+ channels.email = row.email_per_day;
48
+ return { max_per_day: row.max_per_day, max_per_week: row.max_per_week, channels };
49
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@appgrowstack/app-contract",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "description": "appgrowstack の約束の型。schema から作った型・APPGROWSTACK の RPC の型・HTTP の API の型・D1 の表の定義・出来事の名前",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/appgrowstack/app-growth.git",
10
+ "directory": "packages/contract"
11
+ },
12
+ "homepage": "https://github.com/appgrowstack/app-growth/tree/main/packages/contract#readme",
13
+ "keywords": [
14
+ "cloudflare-workers",
15
+ "appgrowstack",
16
+ "types"
17
+ ],
18
+ "sideEffects": false,
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "default": "./dist/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "CHANGELOG.md",
29
+ "LICENSE"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "types": "./dist/index.d.ts",
35
+ "module": "./dist/index.js"
36
+ }