@aiquants/daily-report 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +229 -8
  2. package/dist/client.d.mts +201 -739
  3. package/dist/client.d.ts +201 -739
  4. package/dist/client.js +5 -6
  5. package/dist/client.mjs +5 -6
  6. package/dist/index.d.mts +5 -197
  7. package/dist/index.d.ts +5 -197
  8. package/dist/index.js +1 -2
  9. package/dist/index.mjs +1 -2
  10. package/dist/logger-D3krZrNK.d.mts +0 -14
  11. package/dist/logger-D3krZrNK.d.ts +0 -14
  12. package/dist/server.d.mts +114 -744
  13. package/dist/server.d.ts +114 -744
  14. package/dist/server.js +1 -2
  15. package/dist/server.mjs +1 -2
  16. package/dist/{sse-schema-ChSFm-4q.d.mts → sse-schema-DCxpdETM.d.mts} +1106 -1090
  17. package/dist/{sse-schema-BdUGThiz.d.ts → sse-schema-DoQw8_om.d.ts} +1106 -1090
  18. package/dist/types-CqgYQgbH.d.mts +0 -34
  19. package/dist/types-CqgYQgbH.d.ts +0 -34
  20. package/package.json +9 -10
  21. package/dist/client.js.map +0 -1
  22. package/dist/client.mjs.map +0 -1
  23. package/dist/index.js.map +0 -1
  24. package/dist/index.mjs.map +0 -1
  25. package/dist/server.js.map +0 -1
  26. package/dist/server.mjs.map +0 -1
  27. package/src/client/components/business-day-thumb-overlay.tsx +0 -19
  28. package/src/client/components/daily-report-attachment-indicator.spec.tsx +0 -51
  29. package/src/client/components/daily-report-attachment-indicator.tsx +0 -45
  30. package/src/client/components/daily-report-attachment-list.spec.tsx +0 -94
  31. package/src/client/components/daily-report-attachment-list.tsx +0 -112
  32. package/src/client/components/daily-report-comment-item.tsx +0 -89
  33. package/src/client/components/daily-report-comment-section.tsx +0 -166
  34. package/src/client/components/daily-report-detail-list.tsx +0 -842
  35. package/src/client/components/daily-report-edit-form.tsx +0 -87
  36. package/src/client/components/daily-report-ids-stream-status.spec.tsx +0 -93
  37. package/src/client/components/daily-report-ids-stream-status.tsx +0 -67
  38. package/src/client/components/daily-report-list.tsx +0 -1232
  39. package/src/client/components/daily-report-page.spec.tsx +0 -119
  40. package/src/client/components/daily-report-page.tsx +0 -140
  41. package/src/client/components/daily-report-resize-panels.spec.tsx +0 -307
  42. package/src/client/components/daily-report-resolved-content.tsx +0 -207
  43. package/src/client/components/daily-report-scroll-restoration.spec.tsx +0 -422
  44. package/src/client/components/report-views.spec.tsx +0 -375
  45. package/src/client/components/unread-indicator.tsx +0 -13
  46. package/src/client/config-context.tsx +0 -184
  47. package/src/client/contexts/daily-report-action-context.spec.tsx +0 -433
  48. package/src/client/contexts/daily-report-action-context.tsx +0 -1147
  49. package/src/client/contexts/daily-report-error-context.spec.tsx +0 -66
  50. package/src/client/contexts/daily-report-error-context.tsx +0 -98
  51. package/src/client/hooks/use-animated-number.spec.ts +0 -103
  52. package/src/client/hooks/use-animated-number.ts +0 -69
  53. package/src/client/hooks/use-daily-report-comments.ts +0 -73
  54. package/src/client/hooks/use-daily-report-sse-connection.ts +0 -86
  55. package/src/client/hooks/use-daily-report.spec.ts +0 -546
  56. package/src/client/hooks/use-daily-report.ts +0 -549
  57. package/src/client/hooks/use-dynamic-viewport-height.ts +0 -127
  58. package/src/client/hooks/use-responsive-layout.spec.ts +0 -74
  59. package/src/client/hooks/use-responsive-layout.ts +0 -63
  60. package/src/client/route-helpers.spec.ts +0 -100
  61. package/src/client/route-helpers.ts +0 -61
  62. package/src/client/streaming/daily-report-ids-stream-client.spec.ts +0 -910
  63. package/src/client/streaming/daily-report-ids-stream-client.ts +0 -730
  64. package/src/client/streaming/daily-report-ids-stream-session.spec.ts +0 -401
  65. package/src/client/streaming/daily-report-ids-stream-session.ts +0 -319
  66. package/src/client/ui/button.tsx +0 -42
  67. package/src/client/ui/cn.ts +0 -14
  68. package/src/client/ui/input.tsx +0 -21
  69. package/src/client/ui/label.tsx +0 -16
  70. package/src/client/ui/switch.tsx +0 -19
  71. package/src/client/ui/tabs.tsx +0 -40
  72. package/src/client/ui/textarea.tsx +0 -19
  73. package/src/client/utils/constants.spec.ts +0 -96
  74. package/src/client/utils/constants.ts +0 -84
  75. package/src/client.ts +0 -28
  76. package/src/index.ts +0 -11
  77. package/src/lucide-icons.d.ts +0 -6
  78. package/src/server/authz.spec.ts +0 -57
  79. package/src/server/authz.ts +0 -99
  80. package/src/server/cache.spec.ts +0 -556
  81. package/src/server/cache.ts +0 -303
  82. package/src/server/etag.ts +0 -18
  83. package/src/server/external-source.ts +0 -60
  84. package/src/server/handlers.action.spec.ts +0 -44
  85. package/src/server/handlers.attachment.spec.ts +0 -470
  86. package/src/server/handlers.ids-stream.spec.ts +0 -618
  87. package/src/server/handlers.ts +0 -1638
  88. package/src/server/handlers.unauthorized-cookie.spec.ts +0 -187
  89. package/src/server/handlers.visibility.spec.ts +0 -774
  90. package/src/server/ports.ts +0 -222
  91. package/src/server/response.ts +0 -37
  92. package/src/server/schema.spec.ts +0 -30
  93. package/src/server/schema.ts +0 -344
  94. package/src/server/service.spec.ts +0 -1130
  95. package/src/server/service.ts +0 -2045
  96. package/src/server/sse-reader.spec.ts +0 -302
  97. package/src/server/sse-reader.ts +0 -267
  98. package/src/server/test-helpers/handlers-config.ts +0 -321
  99. package/src/server/transaction-retry.spec.ts +0 -63
  100. package/src/server/visibility.spec.ts +0 -403
  101. package/src/server/visibility.ts +0 -373
  102. package/src/server.spec.ts +0 -160
  103. package/src/server.ts +0 -131
  104. package/src/shared/business-date.spec.ts +0 -82
  105. package/src/shared/business-date.ts +0 -104
  106. package/src/shared/comment-adapter.spec.ts +0 -38
  107. package/src/shared/comment-adapter.ts +0 -80
  108. package/src/shared/ids-stream.spec.ts +0 -154
  109. package/src/shared/ids-stream.ts +0 -279
  110. package/src/shared/logger.ts +0 -47
  111. package/src/shared/sse-schema.spec.ts +0 -50
  112. package/src/shared/sse-schema.ts +0 -198
  113. package/src/shared/text-utils.spec.ts +0 -42
  114. package/src/shared/text-utils.ts +0 -65
  115. package/src/shared/types.ts +0 -109
  116. package/src/styles/standalone.entry.css +0 -51
@@ -1,373 +0,0 @@
1
- /**
2
- * Source-type visibility set: normalization, digest, and predicate helpers.
3
- * sourceType 可視集合の正規化・ダイジェスト・判定ヘルパー群。
4
- *
5
- * 中立文字列 (`DailyReportHub.sourceType` の値) のみを扱い、いかなる認可パッケージの型にも
6
- * 依存しない。可視集合は 2 状態を厳密に区別する:
7
- *
8
- * - `null` = 無制限 (全件)。ポート未注入時の既定であり、現行互換の意味を持つ。
9
- * - `Set` = その集合に限定。**空集合は 0 件 (fail-close)** であって無制限ではない。
10
- *
11
- * この 2 状態の取り違えは情報漏洩か機能停止に直結するため、判定・畳み込み・キー生成を
12
- * 本ファイルへ一元化し、ハンドラ層とサービス層の双方がここだけを参照する。
13
- *
14
- * 閲覧範囲は**次元ごと**にこの 2 状態を持つ:
15
- *
16
- * - `visible` = 本文 (日報行) を閲覧してよい区分。
17
- * - `commentable` = コメントを閲覧・記入してよい区分。常に `visible` の部分集合。
18
- *
19
- * 次元が増えても状態数は増やさない。「もう一方の次元に従う」は
20
- * {@link DailyReportViewerScope.restrictTo} が**構築時に解決**するため、各次元は最後まで
21
- * 厳密に 2 状態であり、本ファイルの判定ヘルパーは次元を問わずそのまま適用できる。
22
- */
23
- import { inArray, type SQL, sql } from "drizzle-orm"
24
- import type { AnyMsSqlColumn } from "drizzle-orm/mssql-core"
25
- import type { DailyReportVisibilityDimensions } from "./ports"
26
-
27
- /**
28
- * Normalized visible set. null = unrestricted (all rows), ReadonlySet = restricted (empty = zero rows).
29
- * 正規化済みの可視集合。null は無制限 (全件)、ReadonlySet は限定 (空集合は 0 件)。
30
- */
31
- export type VisibleSourceTypeSet = ReadonlySet<string> | null
32
-
33
- /**
34
- * Separator for digest concatenation; never occurs inside a sourceType value.
35
- * ダイジェスト連結用の区切り文字。sourceType の値には決して現れない制御文字。
36
- */
37
- const DIGEST_SEPARATOR = "\u0001"
38
-
39
- /**
40
- * Maximum digest length before falling back to a hash.
41
- * ハッシュへ退避する前のダイジェスト最大長。
42
- *
43
- * キャッシュキーが際限なく伸びるのを防ぐだけの閾値であり、通常の区分数 (数個) では到達しない。
44
- */
45
- const DIGEST_RAW_MAX_LENGTH = 64
46
-
47
- /**
48
- * Folds a stored sourceType value into its comparison key (case-insensitive only).
49
- * 格納済みの sourceType 値を比較キーへ畳み込む処理 (大小文字非依存のみ)。
50
- *
51
- * ❗ ここで `trim()` してはならない。SQL 側の述語は `LOWER(source_type)` だけを掛けており
52
- * 列値をトリムしないため、JS 側だけ切り詰めると同じ行について SSE (JS 判定) は可視・
53
- * 読み取り (SQL 判定) は不可視という乖離が生まれる (SSE が fail-open 側へずれる)。
54
- * 両者を「列値は畳み込むだけ」に揃え、空白混じりの値は双方で不可視 = fail-close とする。
55
- */
56
- const foldStoredSourceType = (raw: string): string => raw.toLowerCase()
57
-
58
- /**
59
- * Folds a resolver-supplied token into its comparison key (trimmed, case-insensitive).
60
- * リゾルバ由来のトークンを比較キーへ畳み込む処理 (前後空白除去・大小文字非依存)。
61
- *
62
- * トークンは人手で設定された設定値であり、前後の空白は書き間違いとして吸収してよい。
63
- * 一方で列値 ({@link foldStoredSourceType}) は DB のデータなので勝手に切り詰めない。
64
- */
65
- const foldResolverToken = (raw: string): string => raw.trim().toLowerCase()
66
-
67
- /**
68
- * Normalizes a raw resolver return into a VisibleSourceTypeSet.
69
- * ポートの生戻り値を正規化済み可視集合へ変換する処理。
70
- *
71
- * `null` / `undefined` は無制限 (`null`) へ。配列は各要素を畳み込み・空文字除去・重複排除して
72
- * `Set` 化する。**空配列は空 `Set` (0 件) を返し、`null` (無制限) へは決して倒さない** —
73
- * この取り違えが情報漏洩か機能停止に直結するため。
74
- *
75
- * ❗ 引数は**単一次元のトークン配列に限る**。次元別オブジェクト
76
- * ({@link DailyReportVisibilityDimensions}) をここへ渡すと配列ガードに掛かって全拒否になるため、
77
- * 次元の解体は {@link DailyReportViewerScope.restrictTo} が行い、ここには常に配列だけが届く。
78
- *
79
- * ❗ オーバーロードで「**配列を渡した場合は決して `null` (無制限) を返さない**」という不変条件を
80
- * 型に載せている。これは実装の偶然ではなく本ファイルの中核契約 (空配列は 0 件であって無制限では
81
- * ない) そのものであり、呼び出し側が `null` 分岐を書いて無制限へ倒す余地を型で塞ぐ。
82
- *
83
- * @param raw Raw single-dimension resolver value. 単一次元の生値。
84
- * @returns Normalized visible set. 正規化済みの可視集合。
85
- */
86
- export function normalizeVisibleSourceTypes(raw: readonly string[]): ReadonlySet<string>
87
- export function normalizeVisibleSourceTypes(raw: readonly string[] | null | undefined): VisibleSourceTypeSet
88
- export function normalizeVisibleSourceTypes(raw: readonly string[] | null | undefined): VisibleSourceTypeSet {
89
- if (raw == null) {
90
- return null
91
- }
92
- // 配列以外 (契約違反。例: リゾルバが誤って文字列 "NI" を返す) は fail-close で空集合にする。
93
- // ガードが無いと `for...of "NI"` が文字単位で反復し {"n","i"} という誤った可視集合になる
94
- if (!Array.isArray(raw)) {
95
- return new Set<string>()
96
- }
97
- const set = new Set<string>()
98
- for (const token of raw) {
99
- // 非文字列要素は黙って捨てる (可視性を広げる方向には決して働かない)
100
- if (typeof token !== "string") {
101
- continue
102
- }
103
- const folded = foldResolverToken(token)
104
- if (folded.length > 0) {
105
- set.add(folded)
106
- }
107
- }
108
- return set
109
- }
110
-
111
- /**
112
- * Tests whether a report's sourceType is visible under the given set.
113
- * ある日報の sourceType が可視集合に含まれるかの三値判定。
114
- *
115
- * - 無制限 (`null`): 常に `true`。
116
- * - 限定 + sourceType 判明: 畳み込み一致で判定。
117
- * - 限定 + sourceType 不明 (`null` / `undefined`): `false` — 制限された閲覧者は「不明な区分」を
118
- * 見られない。区分を運ばない旧 SSE エントリ等を fail-close 側へ倒すための規則。
119
- *
120
- * @param set Normalized visible set. 正規化済みの可視集合。
121
- * @param sourceType The row's source type, if known. 判明していれば当該行のソース種別。
122
- * @returns True when visible. 可視なら true。
123
- */
124
- export function isSourceTypeVisible(set: VisibleSourceTypeSet, sourceType: string | null | undefined): boolean {
125
- if (set === null) {
126
- return true
127
- }
128
- if (sourceType == null) {
129
- return false
130
- }
131
- return set.has(foldStoredSourceType(sourceType))
132
- }
133
-
134
- /**
135
- * Tells whether the set denies everything (zero rows).
136
- * 可視集合が全拒否 (0 件) を意味するかを判定する処理。
137
- *
138
- * 真のとき呼び出し側は DB へ問い合わせず即座に空を返してよい (無駄クエリの排除)。
139
- * これは性能上の短絡であり、認可の防御そのものは {@link buildVisibleSourceTypeCondition} が担う。
140
- *
141
- * @param set Normalized visible set. 正規化済みの可視集合。
142
- * @returns True when nothing is visible. 何も可視でないなら true。
143
- */
144
- export function deniesEverySourceType(set: VisibleSourceTypeSet): boolean {
145
- return set !== null && set.size === 0
146
- }
147
-
148
- /**
149
- * Builds the SQL condition restricting rows to the visible source types.
150
- * 可視 sourceType へ行を限定する SQL 条件を生成する処理 (三値)。
151
- *
152
- * {@link isSourceTypeVisible} の SQL 版であり、同じ三値を同じ向きへ写像する:
153
- *
154
- * - 無制限 (`null`): `undefined` を返す。drizzle の `and(...)` は `undefined` を無視するため、
155
- * 既存の述語がそのまま残る (現行互換)。
156
- * - 全拒否 (空集合): `1 = 0` を返す。**決して `undefined` へ倒さない** — 呼び出し側の短絡漏れが
157
- * あっても生成器自身が fail-close する二重防御であり、ここを緩めると認可が反転する。
158
- * - 限定: `LOWER(<column>) IN (...)`。トークンは正規化時に小文字畳み込み済みなので両辺が小文字となり、
159
- * DB の照合順序 (collation) に依存せず決定的に大小文字非依存で一致する。
160
- *
161
- * @param sourceTypeColumn The source-type column to constrain. 制限対象の sourceType 列。
162
- * @param set Normalized visible set. 正規化済みの可視集合。
163
- * @returns Condition, or undefined when unrestricted. 条件 (無制限なら undefined)。
164
- */
165
- export function buildVisibleSourceTypeCondition(sourceTypeColumn: AnyMsSqlColumn, set: VisibleSourceTypeSet): SQL | undefined {
166
- if (set === null) {
167
- return undefined
168
- }
169
- if (set.size === 0) {
170
- return sql`1 = 0`
171
- }
172
- return inArray(sql`LOWER(${sourceTypeColumn})`, [...set])
173
- }
174
-
175
- /**
176
- * Request-scoped viewer scope carrying the normalized visible source-type set.
177
- * 正規化済みの可視 sourceType 集合を運ぶ、リクエストスコープの閲覧範囲。
178
- *
179
- * このクラスは private フィールドを持つことで**名目型**になっており、`{ visible: null }` のような
180
- * 構造的偽造も、`{ ...scope, visible: null }` のようなスプレッドによる widening も型が拒否する
181
- * (`unique symbol` ブランドでは後者を防げないことを実測で確認済み)。
182
- *
183
- * 生成経路は {@link DailyReportViewerScope.restrictTo} と {@link DailyReportViewerScope.unrestricted}
184
- * の 2 つだけであり、`null` を「可視性」としてそのまま綴ることはできない。結果として、
185
- * **絞り込まれない読み取りは必ず `unrestricted(理由)` として現れる**ため、
186
- * `grep -rn "DailyReportViewerScope.unrestricted("` が fail-open の全数リストになる。
187
- */
188
- export class DailyReportViewerScope {
189
- /**
190
- * 正規化済みの本文可視集合を保持する private スロット。
191
- *
192
- * ❗ public な読み取り専用プロパティにしてはならない。`readonly` は型のみの制約であり、
193
- * `Object.assign(scope, { visible: null })` は型検査も実行時も素通りして実体を書き換える
194
- * (実測済み)。private スロット + getter なら代入が実行時にも失敗する。
195
- */
196
- readonly #visible: VisibleSourceTypeSet
197
-
198
- /**
199
- * 正規化済みのコメント可視集合を保持する private スロット。
200
- *
201
- * 構築時に確定済みであり、`#visible` と同じ 2 状態しか取らない (`null` = 無制限 / `Set` = 限定)。
202
- * 「`read` に従う」を遅延 sentinel として保持すると次元あたり 3 状態目が生まれ、判定・畳み込み・
203
- * キー生成の全てを分岐させる必要が出るため、必ず {@link DailyReportViewerScope.restrictTo} で
204
- * 解決してからここへ入れる。
205
- */
206
- readonly #commentable: VisibleSourceTypeSet
207
-
208
- private constructor(visible: VisibleSourceTypeSet, commentable: VisibleSourceTypeSet) {
209
- this.#visible = visible
210
- this.#commentable = commentable
211
- }
212
-
213
- /** 正規化済みの本文可視集合。`null` は無制限、空集合は 0 件 (fail-close)。 */
214
- get visible(): VisibleSourceTypeSet {
215
- // ❗ 実体をそのまま返さない。`ReadonlySet` は型のみの制約で、実体の `Set` は
216
- // `(scope.visible as unknown as Set<string>).add(...)` で in-place に広げられる (実測済み)。
217
- // 毎回コピーを返すことで、外部から可視集合を広げる経路を断つ
218
- return this.#visible === null ? null : new Set(this.#visible)
219
- }
220
-
221
- /**
222
- * 正規化済みのコメント可視集合。`null` は無制限、空集合は 0 件 (fail-close)。
223
- *
224
- * 常に `visible` の部分集合である (構築時に積集合を取っているため)。
225
- */
226
- get commentable(): VisibleSourceTypeSet {
227
- // `visible` と同じ理由でコピーを返す
228
- return this.#commentable === null ? null : new Set(this.#commentable)
229
- }
230
-
231
- /**
232
- * Builds a scope restricted to the given source types (empty input = zero rows).
233
- * 指定した sourceType へ限定した閲覧範囲を生成する処理 (空入力は 0 件)。
234
- *
235
- * 入力は {@link normalizeVisibleSourceTypes} を通るため、大小文字・前後空白・重複・非文字列は
236
- * ここで吸収される。素の配列は `{ read: <配列> }` と同義で、コメント次元は `read` に従う。
237
- *
238
- * ❗ 引数は `null` / `undefined` を**受け付けない**。受け付けると「restrict」という名前のまま
239
- * 無制限スコープを生む第 2 の入口になり、「絞り込まれない読み取りは必ず
240
- * {@link DailyReportViewerScope.unrestricted} に現れる」という監査不変条件が崩れる。
241
- * 無制限は必ず理由付きで明示すること。
242
- *
243
- * ❗ 判別に `Array.isArray` を使ってはならない。型述語が `arg is any[]` であり
244
- * `readonly string[]` を負の分岐から除去できないため、`.read` 参照が TS2339 になる
245
- * (実測済み)。`"read" in input` で判別する。文字列など object でない契約違反入力は
246
- * `in` が実行時に throw するので、先に `typeof` で弾いてから
247
- * {@link normalizeVisibleSourceTypes} の fail-close 経路へ落とす。
248
- *
249
- * @param input Visible source-type tokens, or per-dimension sets. 可視 sourceType のトークン群、または次元別の集合。
250
- * @returns The scope. 生成した閲覧範囲。
251
- */
252
- static restrictTo(input: readonly string[] | DailyReportVisibilityDimensions): DailyReportViewerScope {
253
- const isDimensions = typeof input === "object" && input !== null && "read" in input
254
- const read = normalizeVisibleSourceTypes(isDimensions ? input.read : input)
255
- // ❗ 実行時に届く値は型より広い (JS 消費側・外部設定由来)。宣言を nullish 込みに広げて
256
- // 「undefined 以外の nullish」を下で明示的に扱う
257
- const rawComment: readonly string[] | null | undefined = isDimensions ? input.comment : undefined
258
- // `comment` 省略時はコメント次元を `read` に従わせる (単一次元指定と同義・現行互換)。
259
- // ❗ `undefined` **だけ**がこの綴り。他の nullish を同じ意味にすると綴りが 2 つになる
260
- if (rawComment === undefined) {
261
- return new DailyReportViewerScope(read, read)
262
- }
263
- const comment = normalizeVisibleSourceTypes(rawComment)
264
- // ❗ `read` との積集合へ狭める。コメントは必ず read で絞られた詳細の内側にしか載らないため、
265
- // read 外のコメントトークンは意味を持たない。ここで落としておくと、後続の全判定が
266
- // 「commentable ⊆ visible」を前提にできる (設定ミスが可視性を広げる経路が消える)
267
- const narrowed = new Set<string>()
268
- // ❗ `?? []` は死んだ分岐ではない。`normalizeVisibleSourceTypes` は nullish を**無制限**へ
269
- // 写すため、契約違反の `comment: null` をそのまま採ると read より広い集合が生まれる
270
- // (fail-open)。ここで空反復へ倒し、全拒否 = fail-close に揃える
271
- for (const token of comment ?? []) {
272
- if (read.has(token)) {
273
- narrowed.add(token)
274
- }
275
- }
276
- return new DailyReportViewerScope(read, narrowed)
277
- }
278
-
279
- /**
280
- * Builds an unrestricted scope; every call site is an audited fail-open.
281
- * 無制限の閲覧範囲を生成する処理。全呼び出し箇所が監査対象の fail-open となる。
282
- *
283
- * ❗ 理由文字列は必須。読み捨てるが、呼び出し箇所の全数列挙と「なぜここは絞らなくてよいか」の
284
- * 記録を強制するために受け取る。
285
- *
286
- * ❗ **両次元**を無制限にする。片方だけ残すと「無制限」という名前が嘘になり、監査 grep の
287
- * 結果が「絞られていない読み取りの全数」でなくなる。
288
- *
289
- * @param auditReason Why unrestricted access is correct here. なぜここで無制限が正当かの理由。
290
- * @returns The unrestricted scope. 無制限の閲覧範囲。
291
- */
292
- static unrestricted(auditReason: string): DailyReportViewerScope {
293
- void auditReason
294
- return new DailyReportViewerScope(null, null)
295
- }
296
- }
297
-
298
- /**
299
- * Computes the cache-key digest for a whole viewer scope (all dimensions).
300
- * 閲覧範囲全体 (全次元) からキャッシュキー用ダイジェストを算出する処理。
301
- *
302
- * スコープに次元が増えてもキャッシュキーの生成点を 1 つに保つための入口。
303
- *
304
- * ❗ **必ず全次元を畳み込むこと。** 本文次元だけを畳み込むと、コメント権限だけを剥奪された
305
- * 同一ユーザーが剥奪前のキャッシュバケットを共有し続け、TTL の間コメント本文入りの詳細を
306
- * 受け取り続ける (キーが変わらないため無効化も走らない)。
307
- *
308
- * 両次元が一致する既定形 (コメント次元が `read` に従う) では**本文のみのダイジェストと同一値**を
309
- * 返す。既存配備のキャッシュキーは 1 文字も変わらず、キャッシュ再利用率は無退行となる。
310
- * 次元が分かれるときだけ `d:` 名前空間の下へ**長さ接頭辞付きで連結**するため、写像は単射であり
311
- * sentinel (`all` / `none`) や単一次元表記 (`s:` / `sh:`) と衝突しない。
312
- *
313
- * @param scope Viewer scope. 閲覧範囲。
314
- * @returns Digest usable as a cache-key component. キャッシュキー構成要素として使えるダイジェスト。
315
- */
316
- export function computeViewerScopeDigest(scope: DailyReportViewerScope): string {
317
- const read = computeSourceTypeDigest(scope.visible)
318
- const comment = computeSourceTypeDigest(scope.commentable)
319
- // 既定 (コメント次元が read に従う) では現行キーと完全同一にする
320
- if (read === comment) {
321
- return read
322
- }
323
- // ❗ 長さ接頭辞が必須。素の連結では ("s:x", "y") と ("s:xy", "") のような異なる組が
324
- // 同じ文字列になりうる (単射でなくなり、別権限の閲覧者が同一バケットを共有する)
325
- return `d:${read.length}:${read}${comment}`
326
- }
327
-
328
- /**
329
- * Computes a stable and bounded cache-key digest of the set.
330
- * 可視集合から安定・有界なキャッシュキー用ダイジェストを算出する処理。
331
- *
332
- * 無制限は `"all"`、空集合は `"none"`、それ以外は `s:` 名前空間の下へ**長さ接頭辞付きトークンを昇順連結**する。
333
- * 連結は長さ接頭辞付きなので**単射**であり、通常経路 (`s:`) では論理的に等価な集合が必ず同一の、
334
- * 異なる集合が必ず別のダイジェストになる。sentinel (`all` / `none`) とも名前空間が分かれるため、
335
- * 限定集合が無制限 / 全拒否と同じバケットを共有することはない。権限が安定している間はキーが
336
- * 不変になるため、キャッシュは完全に再利用される (性能無退行)。
337
- *
338
- * ❗ 区分数が異常に多い場合だけキー長を抑えるため FNV-1a 32bit へ退避し `sh:` 接頭辞を付ける。
339
- * **この退避経路に限り理論上の衝突がありうる** (32bit)。衝突しても影響は同一ユーザーの
340
- * キャッシュ再利用に留まり、認可判定そのものは SQL 述語が担うため漏洩には至らない。
341
- * 通常の区分数 (数個) では到達しない。
342
- *
343
- * @param set Normalized visible set. 正規化済みの可視集合。
344
- * @returns Digest usable as a cache-key component. キャッシュキー構成要素として使えるダイジェスト。
345
- */
346
- export function computeSourceTypeDigest(set: VisibleSourceTypeSet): string {
347
- if (set === null) {
348
- return "all"
349
- }
350
- if (set.size === 0) {
351
- return "none"
352
- }
353
- // 昇順ソートで要素順に依存しないキーにする (同じ集合は常に同じダイジェスト)。
354
- // ❗ 各トークンは長さ接頭辞付きで連結する。素の区切り文字だけでは、区切り文字を含む
355
- // トークンが別の集合と同じ連結結果になりうる (単射でなくなる)
356
- const joined = [...set]
357
- .sort()
358
- .map((token) => `${token.length}:${token}`)
359
- .join(DIGEST_SEPARATOR)
360
- // ❗ 限定集合の名前空間を `s:` で分ける。分けないと、`"all"` や `"none"` へ畳み込まれる
361
- // トークンだけを許された閲覧者が、無制限 / 全拒否と同じキャッシュバケットを共有してしまう
362
- if (joined.length <= DIGEST_RAW_MAX_LENGTH) {
363
- return `s:${joined}`
364
- }
365
- // 長大キーの退避のみハッシュ化する。衝突しても影響は同一ユーザーのキャッシュ再利用に限られ、
366
- // かつ TTL で失効するが、生連結と混同しないよう接頭辞で区別する
367
- let hash = 0x811c9dc5
368
- for (let i = 0; i < joined.length; i++) {
369
- hash ^= joined.charCodeAt(i)
370
- hash = Math.imul(hash, 0x01000193)
371
- }
372
- return `sh:${(hash >>> 0).toString(16)}`
373
- }
@@ -1,160 +0,0 @@
1
- /**
2
- * Facade tests for createDailyReportServer: the wiring the explicit-enumeration call must forward.
3
- * createDailyReportServer ファサードのテスト。明示列挙の結線が取りこぼしていないことを固定する。
4
- */
5
- import { bigint, mssqlSchema, nvarchar, primaryKey } from "drizzle-orm/mssql-core"
6
- import { describe, expect, it } from "vitest"
7
- import { createDailyReportServer, type DailyReportDb } from "./server"
8
- import { defineDailyReportSchema } from "./server/schema"
9
-
10
- const testUsers = mssqlSchema("test").table("Users", { id: bigint("id", { mode: "number" }).notNull(), displayName: nvarchar("display_name", { length: 100 }) }, (t) => [primaryKey({ columns: [t.id] })])
11
- const tables = defineDailyReportSchema("test", { userTable: testUsers })
12
-
13
- /** どのクエリも空行を返す最小 db (clearCache 経路は DB に触れない)。 */
14
- const noopDb = { select: () => ({ from: () => ({ where: () => Promise.resolve([]), top: () => ({ from: () => ({ where: () => Promise.resolve([]) }) }) }) }) } as unknown as DailyReportDb
15
-
16
- /** clearCache の POST 引数。 */
17
- const clearCacheArgs = () => {
18
- const body = new FormData()
19
- body.set("intent", "clearCache")
20
- return { request: new Request("http://localhost/daily_report/api/action", { method: "POST", body }), params: { endpoint: "action" } as Record<string, string | undefined> }
21
- }
22
-
23
- /** redis 未注入警告をテスト出力へ撒かない静音ロガー。 */
24
- const silentLogger = { debug: () => {}, info: () => {}, warn: () => {}, error: () => {} }
25
-
26
- const makeServer = (enableDevCacheClear?: boolean) =>
27
- createDailyReportServer({
28
- db: noopDb,
29
- tables,
30
- userTable: testUsers,
31
- resolveUserId: async () => 8,
32
- encodeUserId: (id) => `ENC${id}`,
33
- authenticate: async () => ({ user: { id: "ext-8" }, cookie: undefined }),
34
- draftLabelName: "draft",
35
- enableDevCacheClear,
36
- logger: silentLogger,
37
- })
38
-
39
- describe("createDailyReportServer: enableDevCacheClear の結線", () => {
40
- it("既定 (未指定) では clearCache を 400 で拒否する", async () => {
41
- const server = makeServer()
42
- const res = await server.api.action(clearCacheArgs())
43
- expect(res.status).toBe(400)
44
- })
45
-
46
- it("enableDevCacheClear:true をファサードへ渡すとハンドラまで伝播し 200 になる", async () => {
47
- // ❗ この経路が createDailyReportServer の明示列挙で取りこぼされると、アプリが
48
- // フラグを渡しても黙って無視される (回帰検知の要)
49
- const server = makeServer(true)
50
- const res = await server.api.action(clearCacheArgs())
51
- expect(res.status).toBe(200)
52
- })
53
- })
54
-
55
- describe("createDailyReportServer: resolveVisibleSourceTypes の結線", () => {
56
- /** ポートを注入したファサードを組み立てる。 */
57
- const makeServerWithPort = (resolveVisibleSourceTypes?: () => Promise<string[]>) =>
58
- createDailyReportServer({
59
- db: noopDb,
60
- tables,
61
- userTable: testUsers,
62
- resolveUserId: async () => 8,
63
- encodeUserId: (id) => `ENC${id}`,
64
- authenticate: async () => ({ user: { id: "ext-8" }, cookie: undefined }),
65
- draftLabelName: "draft",
66
- resolveVisibleSourceTypes,
67
- logger: silentLogger,
68
- })
69
-
70
- /** 読み取り API の引数。 */
71
- const readArgs = () => ({
72
- request: new Request("http://localhost/daily_report/api/business-date?businessDate=2099-01-05"),
73
- params: { endpoint: "business-date" } as Record<string, string | undefined>,
74
- })
75
-
76
- it("注入したポートがハンドラまで伝播して呼ばれる", async () => {
77
- // ❗ createDailyReportServer の明示列挙からこの 1 行が落ちると、アプリがポートを
78
- // 注入しても黙って捨てられ、区分フィルタが効かないまま全件配信になる (認可バイパス)
79
- let calls = 0
80
- const server = makeServerWithPort(async () => {
81
- calls += 1
82
- return ["NI"]
83
- })
84
-
85
- await server.api.loader(readArgs())
86
-
87
- expect(calls).toBe(1)
88
- })
89
-
90
- // 未注入時に無制限 (null) が全経路へ渡ることは handlers.visibility.spec.ts が
91
- // サービス受領引数レベルで固定しているため、ここでは転送の有無だけを見る
92
- })
93
-
94
- describe("createDailyReportServer: knownSourceTypes", () => {
95
- it("externalSources の sourceType と Internal を重複なく公開する", () => {
96
- const server = createDailyReportServer({
97
- db: noopDb,
98
- tables,
99
- userTable: testUsers,
100
- resolveUserId: async () => 8,
101
- encodeUserId: (id) => `ENC${id}`,
102
- authenticate: async () => ({ user: { id: "ext-8" }, cookie: undefined }),
103
- draftLabelName: "draft",
104
- externalSources: [
105
- { sourceType: "NI", table: {}, idColumn: tables.hub.id, mapRow: () => ({}) },
106
- { sourceType: "kintone", table: {}, idColumn: tables.hub.id, mapRow: () => ({}) },
107
- ],
108
- })
109
-
110
- expect([...server.knownSourceTypes].sort()).toEqual(["Internal", "NI", "kintone"].sort())
111
- })
112
-
113
- it("externalSources 未注入でも Internal だけは必ず含む", () => {
114
- const server = createDailyReportServer({
115
- db: noopDb,
116
- tables,
117
- userTable: testUsers,
118
- resolveUserId: async () => 8,
119
- encodeUserId: (id) => `ENC${id}`,
120
- authenticate: async () => ({ user: { id: "ext-8" }, cookie: undefined }),
121
- draftLabelName: "draft",
122
- })
123
-
124
- expect([...server.knownSourceTypes]).toEqual(["Internal"])
125
- })
126
- })
127
-
128
- describe("redis 未注入の起動警告", () => {
129
- /** 記録するロガー。 */
130
- const makeRecordingLogger = () => {
131
- const warns: unknown[][] = []
132
- return {
133
- logger: { debug: () => {}, info: () => {}, warn: (...args: unknown[]) => void warns.push(args), error: () => {} },
134
- warns,
135
- }
136
- }
137
-
138
- const baseConfig = () => ({
139
- db: noopDb,
140
- tables,
141
- userTable: testUsers,
142
- resolveUserId: async () => 8,
143
- encodeUserId: (id: number) => `ENC${id}`,
144
- authenticate: async () => ({ user: { id: "ext-8" }, cookie: undefined }),
145
- draftLabelName: "draft",
146
- })
147
-
148
- it("redis 未注入なら警告を 1 度だけ出す (無効化されたことがどこにも現れない状態を作らない)", () => {
149
- const { logger, warns } = makeRecordingLogger()
150
- createDailyReportServer({ ...baseConfig(), logger })
151
- expect(warns.filter((args) => String(args[0]).includes("redis provider is not injected"))).toHaveLength(1)
152
- })
153
-
154
- it("redis を注入すれば警告は出ない", () => {
155
- const { logger, warns } = makeRecordingLogger()
156
- const redis = { getClient: async () => ({ get: async () => null }) }
157
- createDailyReportServer({ ...baseConfig(), logger, redis: redis as never })
158
- expect(warns.filter((args) => String(args[0]).includes("redis provider is not injected"))).toHaveLength(0)
159
- })
160
- })
package/src/server.ts DELETED
@@ -1,131 +0,0 @@
1
- /**
2
- * Server entry of @aiquants/daily-report: schema factory, service, SSE reader, and handler factories.
3
- * @aiquants/daily-report の server エントリ。スキーマファクトリ・サービス・SSE リーダー・ハンドラ工場を公開。
4
- */
5
- import { createEpochStore, SqlResultCache } from "./server/cache"
6
- import type { DailyReportExternalSource } from "./server/external-source"
7
- import { createDailyReportHandlers } from "./server/handlers"
8
- import type { DailyReportAuthenticate, DailyReportReadAttachment, DailyReportResolveVisibleSourceTypes } from "./server/ports"
9
- import { createDailyReportService, type DailyReportServiceConfig } from "./server/service"
10
- import { DailyReportSseReader } from "./server/sse-reader"
11
-
12
- export * from "./server/authz"
13
- export * from "./server/cache"
14
- export { generateETag } from "./server/etag"
15
- export * from "./server/external-source"
16
- export * from "./server/handlers"
17
- export * from "./server/ports"
18
- export * from "./server/response"
19
- export * from "./server/schema"
20
- export * from "./server/service"
21
- export * from "./server/sse-reader"
22
- export * from "./server/visibility"
23
-
24
- /** createDailyReportServer の設定 (サービス設定 + 認証ポート + ハンドラ設定)。 */
25
- export type DailyReportServerConfig = Omit<DailyReportServiceConfig, "cache" | "epochs"> & {
26
- /** リクエスト認証ポート。 */
27
- authenticate: DailyReportAuthenticate
28
- /**
29
- * 可視 sourceType リゾルバ。未注入なら全件 (現行互換)。
30
- *
31
- * サーバー側の全データ経路 (一覧 / 詳細 / コメント / 添付 / SSE) に一貫して効く。
32
- * 戻り値は `DailyReportHub.sourceType` の値 (`knownSourceTypes` 参照) であり、認可リソースキーではない。
33
- * `undefined` / `null` は無制限、空配列は 0 件、例外は全拒否 (fail-close)。
34
- */
35
- resolveVisibleSourceTypes?: DailyReportResolveVisibleSourceTypes
36
- /** 添付ファイル読み取りポート。未注入なら添付エンドポイントは常に 404。 */
37
- readAttachment?: DailyReportReadAttachment
38
- /** 添付ファイルの最大バイト数 (既定 32 MiB)。サービス側のワイヤ上限より低く保つこと。 */
39
- attachmentMaxBytes?: number
40
- /** 添付エンドポイントの 1 分あたり呼び出し上限 (ユーザー単位・既定 60)。 */
41
- attachmentRateLimitPerMinute?: number
42
- /** 添付読み取りの同時実行上限 (プロセス単位・既定 4)。 */
43
- attachmentConcurrency?: number
44
- /** 未ログイン時のリダイレクト先 (index.loader 用、既定 "/auth/login")。 */
45
- loginRedirectPath?: string
46
- /**
47
- * `intent=clearCache` (全サーバーキャッシュの一括破棄) を許可するか。既定 false。
48
- * 開発用アフォーダンス。有効化すると認証済みなら誰でも全ワーカーのキャッシュを
49
- * 無制限破棄できるため、本番では無効のままにする (消費アプリは開発環境のみ true 注入)。
50
- */
51
- enableDevCacheClear?: boolean
52
- /** SQL 結果キャッシュの既定 TTL (既定 60,000ms)。 */
53
- cacheDefaultTtlMs?: number
54
- /** 外部ソースアダプタ群 (レガシー日報テーブル等)。 */
55
- externalSources?: DailyReportExternalSource[]
56
- }
57
-
58
- /**
59
- * One-stop factory wiring cache, service, SSE fan-out reader, and route handlers.
60
- * キャッシュ・サービス・SSE Fan-Out リーダー・ルートハンドラを一括結線するファクトリ。
61
- *
62
- * @example
63
- * const server = createDailyReportServer({ db, tables, userTable, resolveUserId, encodeUserId, authenticate, redis })
64
- * // routes:
65
- * // daily_report._index → server.index.loader (+ data() ラップ)
66
- * // daily_report.api.$endpoint → server.api.loader / server.api.action
67
- * // sse.daily_report.$endpoint → server.sse.loader
68
- */
69
- export function createDailyReportServer(config: DailyReportServerConfig) {
70
- // redis 未注入は単一ワーカーなら正しく動く (プロセス内無効化は効く) が、
71
- // ワーカー横断の無効化と SSE 配信が黙って無効になる。強制はせず、気づける形にする
72
- if (!config.redis) {
73
- const logger = config.logger ?? console
74
- logger.warn("[DailyReport] redis provider is not injected: cross-worker cache invalidation is disabled (staleness is bounded only by TTL) and SSE publishing is skipped.")
75
- }
76
- // epoch ストアと SQL 結果キャッシュ (サービスと SSE リーダーで同一インスタンスを共有する)
77
- const epochs = createEpochStore(config.redis)
78
- const cache = new SqlResultCache({ defaultTtlMs: config.cacheDefaultTtlMs ?? 60_000 }, epochs)
79
-
80
- const service = createDailyReportService({ ...config, cache, epochs })
81
-
82
- const sseReader = new DailyReportSseReader({
83
- redis: config.redis,
84
- streamKey: service.streamKey,
85
- cache,
86
- logger: config.logger,
87
- })
88
-
89
- // ❗ この呼び出しはスプレッドではなく明示列挙である。新しいポートをここへ足し忘れると
90
- // アプリが注入しても黙って捨てられ、添付エンドポイントは永久に 404 を返す。
91
- const handlers = createDailyReportHandlers({
92
- authenticate: config.authenticate,
93
- // ❗ 明示列挙。ここへ足し忘れると注入されたポートが黙って捨てられ、区分フィルタが
94
- // 一切効かないまま全件配信になる (認可バイパス)。server.spec.ts が配線を gate する
95
- resolveVisibleSourceTypes: config.resolveVisibleSourceTypes,
96
- service,
97
- encodeUserId: config.encodeUserId,
98
- attachmentIdCodec: config.attachmentIdCodec,
99
- readAttachment: config.readAttachment,
100
- attachmentMaxBytes: config.attachmentMaxBytes,
101
- attachmentRateLimitPerMinute: config.attachmentRateLimitPerMinute,
102
- attachmentConcurrency: config.attachmentConcurrency,
103
- redis: config.redis,
104
- sseReader,
105
- streamKey: service.streamKey,
106
- loginRedirectPath: config.loginRedirectPath,
107
- enableDevCacheClear: config.enableDevCacheClear,
108
- logger: config.logger,
109
- })
110
-
111
- return {
112
- /** データアクセスサービス (CRUD + キャッシュ + SSE publish)。 */
113
- service,
114
- /** SQL 結果キャッシュ (サービス・SSE リーダー共有インスタンス)。 */
115
- cache,
116
- /** クロスワーカー epoch ストア。 */
117
- epochs,
118
- /** SSE Fan-Out 共有リーダー。 */
119
- sseReader,
120
- /** SSE Redis Stream キー。 */
121
- streamKey: service.streamKey,
122
- /**
123
- * 既知の正準 sourceType 集合 (注入した `externalSources` の全 sourceType + `"Internal"`)。
124
- *
125
- * `resolveVisibleSourceTypes` が返すべき語彙そのものであり、消費側は起動時にこの集合と
126
- * 自前のマッピングを突き合わせて誤トークン (無診断で 0 件になる) を検出できる。
127
- */
128
- knownSourceTypes: [...new Set(["Internal", ...(config.externalSources ?? []).map((source) => source.sourceType)])] as readonly string[],
129
- ...handlers,
130
- }
131
- }