@tpsdev-ai/flair 0.55.2 → 0.57.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 (106) hide show
  1. package/README.md +18 -19
  2. package/dist/bridges/builtins/markdown.js +2 -2
  3. package/dist/bridges/discover.js +2 -2
  4. package/dist/bridges/runtime/allow-list.js +2 -2
  5. package/dist/build-info.json +3 -3
  6. package/dist/cli.js +125 -26
  7. package/dist/commands/agent.js +22 -15
  8. package/dist/commands/attention.js +2 -2
  9. package/dist/commands/backup.js +2 -2
  10. package/dist/commands/bridge.js +40 -3
  11. package/dist/commands/doctor.js +91 -28
  12. package/dist/commands/export.js +2 -2
  13. package/dist/commands/federation.js +441 -68
  14. package/dist/commands/hook.js +4 -4
  15. package/dist/commands/init.js +59 -12
  16. package/dist/commands/mcp.js +2 -2
  17. package/dist/commands/migrate-harness-memory.js +8 -8
  18. package/dist/commands/rem.js +2 -2
  19. package/dist/commands/service.js +25 -1
  20. package/dist/commands/session.js +2 -2
  21. package/dist/commands/uninstall.js +2 -2
  22. package/dist/commands/upgrade.js +3 -3
  23. package/dist/doctor-client.js +5 -23
  24. package/dist/engine-version.js +2 -2
  25. package/dist/federation/scheduler.js +5 -5
  26. package/dist/install/clients.js +5 -10
  27. package/dist/keystore.js +10 -2
  28. package/dist/lib/auth-resolve.js +51 -5
  29. package/dist/lib/doctor-config-path.js +2 -2
  30. package/dist/lib/flair-paths.js +29 -0
  31. package/dist/lib/home.js +60 -0
  32. package/dist/lib/instance-identity-row.js +580 -0
  33. package/dist/lib/launchd-repair.js +6 -0
  34. package/dist/lib/mcp-enable.js +4 -4
  35. package/dist/lib/owned-pins.js +1 -13
  36. package/dist/lib/redact-token-id.js +197 -0
  37. package/dist/lib/socket-path-limit.js +120 -0
  38. package/dist/lib/uninstall-purge.js +2 -18
  39. package/dist/lib/upgrade-plain-tree.js +2 -2
  40. package/dist/mcp-client-assertion.js +3 -3
  41. package/dist/rem/runner.js +3 -3
  42. package/dist/rem/scheduler.js +5 -5
  43. package/dist/rem/snapshot.js +2 -2
  44. package/dist/resources/AgentSeed.js +4 -1
  45. package/dist/resources/Asset.js +3 -11
  46. package/dist/resources/Credential.js +4 -10
  47. package/dist/resources/Federation.js +232 -78
  48. package/dist/resources/Integration.js +8 -32
  49. package/dist/resources/Memory.js +58 -16
  50. package/dist/resources/MemoryBootstrap.js +19 -12
  51. package/dist/resources/MemoryCandidate.js +3 -11
  52. package/dist/resources/MemoryDedupStats.js +1 -1
  53. package/dist/resources/MemoryFeed.js +10 -2
  54. package/dist/resources/MemoryGrant.js +19 -40
  55. package/dist/resources/MemoryUsage.js +7 -20
  56. package/dist/resources/OAuth.js +62 -11
  57. package/dist/resources/Presence.js +135 -47
  58. package/dist/resources/Relationship.js +3 -11
  59. package/dist/resources/SemanticSearch.js +25 -13
  60. package/dist/resources/admin-layout.js +7 -2
  61. package/dist/resources/auth-middleware.js +32 -5
  62. package/dist/resources/bm25.js +13 -14
  63. package/dist/resources/federation-cleanup.js +289 -51
  64. package/dist/resources/health.js +48 -8
  65. package/dist/resources/in-process-api.js +2 -1
  66. package/dist/resources/instance-create-lock.js +363 -0
  67. package/dist/resources/instance-identity-rows.js +43 -0
  68. package/dist/resources/instance-identity.js +94 -10
  69. package/dist/resources/mcp-handler.js +9 -1
  70. package/dist/resources/mcp-tool-arguments.js +83 -0
  71. package/dist/resources/mcp-tools.js +4 -5
  72. package/dist/resources/memory-reflect-lib.js +17 -1
  73. package/dist/resources/memory-visibility.js +10 -7
  74. package/dist/resources/rate-limit.js +6 -4
  75. package/dist/resources/record-type-kit.js +47 -23
  76. package/dist/resources/search-readiness.js +7 -1
  77. package/dist/resources/semantic-retrieval-core.js +98 -3
  78. package/dist/resources/table-helpers.js +33 -0
  79. package/dist/resources/tool-descriptors/index.js +2 -2
  80. package/dist/src/keystore.js +10 -2
  81. package/dist/src/lib/home.js +60 -0
  82. package/dist/src/lib/instance-identity-row.js +580 -0
  83. package/dist/src/lib/redact-token-id.js +197 -0
  84. package/dist/src/rem/scheduler.js +5 -5
  85. package/dist/version-check.js +2 -2
  86. package/dist/version-handshake.js +2 -2
  87. package/docs/api-reference.md +32 -7
  88. package/docs/auth.md +19 -7
  89. package/docs/claude-code.md +5 -6
  90. package/docs/deploying-on-fabric.md +8 -4
  91. package/docs/deployment.md +26 -37
  92. package/docs/embedding-in-a-harper-app.md +4 -2
  93. package/docs/entity-vocabulary.md +5 -5
  94. package/docs/federation.md +48 -21
  95. package/docs/hosted-on-fabric.md +7 -4
  96. package/docs/integrations.md +24 -15
  97. package/docs/mcp-clients.md +44 -23
  98. package/docs/n8n.md +8 -8
  99. package/docs/notes/mcp-oauth-model2.md +12 -17
  100. package/docs/openclaw.md +29 -28
  101. package/docs/spoke-bringup.md +44 -22
  102. package/docs/standalone-local.md +12 -16
  103. package/docs/supply-chain-policy.md +21 -8
  104. package/docs/system-requirements.md +1 -1
  105. package/docs/upgrade.md +2 -2
  106. package/package.json +1 -1
@@ -15,7 +15,7 @@ import { buildCollisionEntries, buildEntityMatchCondition, freshPresenceByAgent,
15
15
  // retrievalCount hit-tracking side effects (see resources/
16
16
  // semantic-retrieval-core.ts's module doc for the full boundary).
17
17
  import { retrieveCandidates, DEFAULT_SELECT } from "./semantic-retrieval-core.js";
18
- import { hybridEnabled } from "./bm25.js";
18
+ import { retrievalMode } from "./bm25.js";
19
19
  import { buildTrustBlock } from "./trust-block.js";
20
20
  import { bestSemanticSimilarity, evaluateAbstention } from "./abstention.js";
21
21
  import { estimateTokens } from "./token-estimate.js";
@@ -939,16 +939,23 @@ export class BootstrapMemories extends Resource {
939
939
  if (currentTask && tokenBudget <= 0)
940
940
  taskRetrievalHint = "Task retrieval skipped: no content budget remains.";
941
941
  if (currentTask && tokenBudget > 0) {
942
+ // Resolve the mode ONCE here so the embedding guard and the core agree.
943
+ // The bm25-only arm ranks on the lexical leg alone and needs NO query
944
+ // embedding — gating it on one being available would skip the lexical
945
+ // search entirely and lose task-relevant memories for no reason.
946
+ const mode = retrievalMode();
942
947
  let queryEmbedding = null;
943
- try {
944
- // flair#504 Phase 2: 'query' — currentTask is the bootstrap's
945
- // task-relevance search query, not stored content.
946
- queryEmbedding = await getEmbedding(currentTask, "query");
948
+ if (mode !== "bm25-only") {
949
+ try {
950
+ // flair#504 Phase 2: 'query' — currentTask is the bootstrap's
951
+ // task-relevance search query, not stored content.
952
+ queryEmbedding = await getEmbedding(currentTask, "query");
953
+ }
954
+ catch { }
947
955
  }
948
- catch { }
949
- if (!queryEmbedding)
956
+ if (mode !== "bm25-only" && !queryEmbedding)
950
957
  taskRetrievalHint = "Task retrieval skipped: query embedding unavailable.";
951
- if (queryEmbedding) {
958
+ if (mode === "bm25-only" || queryEmbedding) {
952
959
  // flair#1207 — exclude own memories ALREADY placed via the authoritative
953
960
  // set (permanent + recent + predicted actually admitted). The old set was
954
961
  // built positionally (recent.filter by index) AND omitted `predicted`, so
@@ -973,9 +980,9 @@ export class BootstrapMemories extends Resource {
973
980
  limit: candidatePoolK,
974
981
  // flair#1246 — ONE RANKER, ONE SCALE: this pass now invokes the
975
982
  // core in the SAME mode memory_search does (hybrid + q via the
976
- // shared hybridEnabled() selector, so the FLAIR_HYBRID_RETRIEVAL
977
- // kill-switch moves BOTH surfaces together — a split mode IS the
978
- // #1246 bug). HNSW-only here was an accident of early code, and it
983
+ // shared retrievalMode() selector, so the FLAIR_RETRIEVAL_MODE /
984
+ // FLAIR_HYBRID_RETRIEVAL kill-switch moves BOTH surfaces together —
985
+ // a split mode IS the #1246 bug). HNSW-only here was an accident of early code, and it
979
986
  // made bootstrap's teammate picks diverge from search on the same
980
987
  // store+query: a record whose task-relevance is LEXICAL (exact task
981
988
  // terms in semantically-atypical prose) ranks BELOW bland-generic
@@ -987,7 +994,7 @@ export class BootstrapMemories extends Resource {
987
994
  // fusion carries it to the top, same as search. Perf (Kern-ratified
988
995
  // trade): the BM25 corpus scan this adds to the bootstrap path is
989
996
  // the same per-call scan every memory_search request already runs.
990
- hybrid: hybridEnabled(),
997
+ mode,
991
998
  // The lexical leg — same query text the embedding was computed
992
999
  // from, so both legs rank the same question (parity with search,
993
1000
  // where `q` drives BM25 and the keyword bump).
@@ -1,7 +1,7 @@
1
1
  import { databases } from "harper";
2
2
  import { resolveAgentAuth } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
- import { makeAuthGate, makeReadScope, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
4
+ import { makeAuthGate, makeReadScope, makeScopedSearch, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
5
5
  import { RECORD_TYPES } from "./record-types.js";
6
6
  // Parameterized from RECORD_TYPES.MemoryCandidate (record-types slice 2,
7
7
  // flair#520) rather than a hand-typed "owner-only" literal — the registry is
@@ -11,6 +11,7 @@ import { RECORD_TYPES } from "./record-types.js";
11
11
  // `.ownerField` against RECORD_TYPES.MemoryCandidate — not for any other
12
12
  // runtime consumer.
13
13
  export const memoryCandidateReadScope = makeReadScope(RECORD_TYPES.MemoryCandidate.readScope, RECORD_TYPES.MemoryCandidate.ownerField);
14
+ const memoryCandidateScopedSearch = makeScopedSearch(memoryCandidateReadScope);
14
15
  const memoryCandidateByIdReadGate = makeByIdReadGate(memoryCandidateReadScope);
15
16
  // See makeAuthGate's doc (record-type-kit.ts): must be wired as a genuine
16
17
  // prototype method below, never a class-field assignment.
@@ -97,16 +98,7 @@ export class MemoryCandidate extends databases.flair.MemoryCandidate {
97
98
  if (gate.kind === "unfiltered")
98
99
  return super.search(query);
99
100
  // Non-admin agent: scope to own candidates only.
100
- const scope = await memoryCandidateReadScope(gate.agentId);
101
- const agentCondition = scope.condition;
102
- if (!query?.conditions) {
103
- return super.search({ conditions: [agentCondition], ...(query || {}) });
104
- }
105
- return super.search({
106
- ...query,
107
- conditions: [agentCondition, { conditions: query.conditions, operator: query.operator || "and" }],
108
- operator: "and",
109
- });
101
+ return memoryCandidateScopedSearch(gate.agentId, query, (q) => super.search(q));
110
102
  }
111
103
  /**
112
104
  * No shipped CLI path calls POST today (the FLAIR-NIGHTLY-REM staging
@@ -131,7 +131,7 @@ async function computeAndPersist(ctx, opts) {
131
131
  queryEmbedding: memory.embedding,
132
132
  conditions: NOT_ARCHIVED,
133
133
  limit: annK + 1,
134
- hybrid: false,
134
+ mode: "vector-only",
135
135
  scoring: "raw",
136
136
  withSemSimilarity: true,
137
137
  select: ["id"],
@@ -1,9 +1,10 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import { Resource, databases } from "harper";
2
3
  import { allowVerified, resolveAgentAuth } from "./agent-auth.js";
3
4
  import { computeContentHash, findExistingMemoryByContentHash } from "./memory-feed-lib.js";
4
5
  import { FORBIDDEN, UNAUTH, stampAttribution } from "./record-type-kit.js";
5
6
  import { guardAuthorityFields, stripAuthorityFields } from "./authority-field-guard.js";
6
- import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY } from "./memory-visibility.js";
7
+ import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
7
8
  import { assertValidDurability } from "./memory-durability.js";
8
9
  import { enforceSkillDurability, refuseSkillWriteSource, skillScanGate } from "./skill-write.js";
9
10
  import { noteMemoryUpsert } from "./bm25-index-service.js";
@@ -49,6 +50,13 @@ export class FeedMemories extends Resource {
49
50
  if (existingRecord && existingRecord.agentId !== content.agentId) {
50
51
  return FORBIDDEN("forbidden: cannot write a feed memory owned by another agent");
51
52
  }
53
+ // Preserve stored visibility on updates before applying write policy
54
+ // (the same rule as Memory.put; only the two writable values).
55
+ if (existingRecord &&
56
+ (content.visibility === undefined || content.visibility === null) &&
57
+ (existingRecord.visibility === PRIVATE_VISIBILITY || existingRecord.visibility === SHARED_VISIBILITY)) {
58
+ content.visibility = existingRecord.visibility;
59
+ }
52
60
  }
53
61
  const agentId = content.agentId;
54
62
  const body = String(content?.content ?? "");
@@ -135,7 +143,7 @@ export class FeedMemories extends Resource {
135
143
  return existing;
136
144
  const record = {
137
145
  ...content,
138
- id: content.id ?? `${agentId}-${Date.now()}`,
146
+ id: content.id ?? `${agentId}-${Date.now()}-${randomUUID()}`,
139
147
  agentId,
140
148
  content: body,
141
149
  contentHash,
@@ -1,6 +1,22 @@
1
1
  import { databases } from "harper";
2
2
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
+ import { makeByIdReadGate, makeScopedSearch } from "./record-type-kit.js";
5
+ // A grant is readable by either party: owner OR grantee. One scope object feeds
6
+ // both the shared by-id gate and the scoped search, so the collection scope is
7
+ // always the outermost AND and the by-id check reads the stored record.
8
+ const grantReadScope = Object.assign(async (agentId) => ({
9
+ condition: {
10
+ operator: "or",
11
+ conditions: [
12
+ { attribute: "ownerId", comparator: "equals", value: agentId },
13
+ { attribute: "granteeId", comparator: "equals", value: agentId },
14
+ ],
15
+ },
16
+ isAllowed: (record) => !!record && (record.ownerId === agentId || record.granteeId === agentId),
17
+ }), { mode: "owner-only", ownerField: "ownerId" });
18
+ const grantByIdReadGate = makeByIdReadGate(grantReadScope);
19
+ const grantScopedSearch = makeScopedSearch(grantReadScope);
4
20
  const FORBIDDEN = (msg) => new Response(JSON.stringify({ error: msg }), { status: 403, headers: { "Content-Type": "application/json" } });
5
21
  const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
6
22
  const NOT_FOUND = () => new Response(JSON.stringify({ error: "not found" }), { status: 404, headers: { "Content-Type": "application/json" } });
@@ -38,31 +54,7 @@ export class MemoryGrant extends databases.flair.MemoryGrant {
38
54
  * to enumerate other agents' grant ids.
39
55
  */
40
56
  async get(target) {
41
- // Collection / query reads arrive as a RequestTarget with
42
- // `isCollection === true`, and are governed by search() (same owner/
43
- // grantee scoping). Only a genuine by-id get is ownership-checked below
44
- // — see Memory.ts's get() for the full rationale (same bug class).
45
- if (!target || (typeof target === "object" && target.isCollection)) {
46
- return this.search(target);
47
- }
48
- const auth = await this._auth();
49
- // Anonymous by-id read is already blocked at the allowRead() gate (403);
50
- // this is defense-in-depth if get() is ever reached directly.
51
- if (auth.kind === "anonymous") {
52
- return NOT_FOUND();
53
- }
54
- // Trusted internal call or admin agent — unfiltered, unchanged behavior.
55
- if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
56
- return super.get(target);
57
- }
58
- // Non-admin agent: visible if it's the owner OR the grantee (parity with
59
- // search()'s owner-OR-grantee scope).
60
- const record = await super.get(target);
61
- if (!record)
62
- return NOT_FOUND();
63
- if (record.ownerId !== auth.agentId && record.granteeId !== auth.agentId)
64
- return NOT_FOUND();
65
- return record;
57
+ return grantByIdReadGate.call(this, target, (t) => super.get(t));
66
58
  }
67
59
  async search(query) {
68
60
  const auth = await this._auth();
@@ -71,21 +63,8 @@ export class MemoryGrant extends databases.flair.MemoryGrant {
71
63
  if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin)) {
72
64
  return super.search(query);
73
65
  }
74
- // owner OR grantee
75
- const scope = {
76
- operator: "or",
77
- conditions: [
78
- { attribute: "ownerId", comparator: "equals", value: auth.agentId },
79
- { attribute: "granteeId", comparator: "equals", value: auth.agentId },
80
- ],
81
- };
82
- if (query && typeof query === "object" && !Array.isArray(query)) {
83
- const existing = query.conditions ?? [];
84
- query.conditions = Array.isArray(existing) ? [scope, ...existing] : [scope, existing];
85
- return super.search(query);
86
- }
87
- const conditions = Array.isArray(query) && query.length > 0 ? [scope, ...query] : [scope];
88
- return super.search(conditions);
66
+ // owner OR grantee, as the outermost AND (makeScopedSearch).
67
+ return grantScopedSearch(auth.agentId, query, (q) => super.search(q));
89
68
  }
90
69
  async post(content, context) {
91
70
  const denied = await this._enforceOwnerWrite(content);
@@ -43,6 +43,11 @@
43
43
  */
44
44
  import { databases } from "harper";
45
45
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
46
+ import { makeByIdReadGate, makeReadScope, makeScopedSearch } from "./record-type-kit.js";
47
+ // Owner-only read scope through the shared by-id gate and scoped search.
48
+ const usageReadScope = makeReadScope("owner-only", "agentId");
49
+ const usageByIdReadGate = makeByIdReadGate(usageReadScope);
50
+ const usageScopedSearch = makeScopedSearch(usageReadScope);
46
51
  const FORBIDDEN = (msg) => new Response(JSON.stringify({ error: msg }), { status: 403, headers: { "Content-Type": "application/json" } });
47
52
  const UNAUTH = () => new Response(JSON.stringify({ error: "authentication required" }), { status: 401, headers: { "Content-Type": "application/json" } });
48
53
  const NOT_FOUND = () => new Response(JSON.stringify({ error: "not found" }), { status: 404, headers: { "Content-Type": "application/json" } });
@@ -52,18 +57,7 @@ export class MemoryUsage extends databases.flair.MemoryUsage {
52
57
  * etc.). Per-record scoping happens in get()/search() below. */
53
58
  allowRead() { return allowVerified(this.getContext?.()); }
54
59
  async get(target) {
55
- if (!target || (typeof target === "object" && target.isCollection)) {
56
- return this.search(target);
57
- }
58
- const auth = await resolveAgentAuth(this.getContext?.());
59
- if (auth.kind === "anonymous")
60
- return NOT_FOUND();
61
- if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin))
62
- return super.get(target);
63
- const record = await super.get(target);
64
- if (!record || record.agentId !== auth.agentId)
65
- return NOT_FOUND();
66
- return record;
60
+ return usageByIdReadGate.call(this, target, (t) => super.get(t));
67
61
  }
68
62
  async search(query) {
69
63
  const auth = await resolveAgentAuth(this.getContext?.());
@@ -71,14 +65,7 @@ export class MemoryUsage extends databases.flair.MemoryUsage {
71
65
  return UNAUTH();
72
66
  if (auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin))
73
67
  return super.search(query);
74
- const scope = { attribute: "agentId", comparator: "equals", value: auth.agentId };
75
- if (query && typeof query === "object" && !Array.isArray(query)) {
76
- const existing = query.conditions ?? [];
77
- query.conditions = Array.isArray(existing) ? [scope, ...existing] : [scope, existing];
78
- return super.search(query);
79
- }
80
- const conditions = Array.isArray(query) && query.length > 0 ? [scope, ...query] : [scope];
81
- return super.search(conditions);
68
+ return usageScopedSearch(auth.agentId, query, (q) => super.search(q));
82
69
  }
83
70
  // Append-only ledger: rows are created via RecordUsage's RAW table call
84
71
  // (bypasses this class entirely — see module doc), never via this
@@ -4,6 +4,7 @@ import { handleJwtBearerGrant } from "./XAA.js";
4
4
  import { resolveAgentAuth } from "./agent-auth.js";
5
5
  import { decideRegistration } from "./dcr-gate.js";
6
6
  import { buildAuthorizationServerMetadata } from "./oauth-discovery.js";
7
+ import { esc } from "./admin-layout.js";
7
8
  /**
8
9
  * OAuth 2.1 Authorization Server for Flair.
9
10
  *
@@ -22,9 +23,32 @@ import { buildAuthorizationServerMetadata } from "./oauth-discovery.js";
22
23
  * - No "remember this decision" — each authorize is explicit
23
24
  */
24
25
  const ALLOWED_REDIRECT_URI = "https://claude.com/api/mcp/auth_callback";
26
+ // The callback's ORIGIN, derived from the SAME constant the redirect_uri check
27
+ // uses — never a second literal. The consent form's POST answers with a 302 to
28
+ // this origin, and `form-action` is enforced across redirects, so it must be an
29
+ // allowed form-action target.
30
+ const ALLOWED_REDIRECT_ORIGIN = new URL(ALLOWED_REDIRECT_URI).origin;
25
31
  const ACCESS_TOKEN_TTL_MS = 3600_000; // 1 hour
26
32
  const REFRESH_TOKEN_TTL_MS = 7 * 86400_000; // 7 days
27
33
  const AUTH_CODE_TTL_MS = 600_000; // 10 minutes
34
+ /**
35
+ * The scopes this server can issue, straight from the authorization-server
36
+ * metadata — ONE source of truth, so the consent page can never render a scope
37
+ * the token endpoint would later refuse.
38
+ */
39
+ const SUPPORTED_SCOPES = new Set(buildAuthorizationServerMetadata().scopes_supported);
40
+ /** `state` is an opaque passthrough: printable ASCII, bounded (RFC 6749 §4.1.2). */
41
+ const STATE_MAX_LENGTH = 512;
42
+ function isOpaqueState(value) {
43
+ if (value.length > STATE_MAX_LENGTH)
44
+ return false;
45
+ for (let i = 0; i < value.length; i++) {
46
+ const c = value.charCodeAt(i);
47
+ if (c < 0x20 || c > 0x7e)
48
+ return false;
49
+ }
50
+ return true;
51
+ }
28
52
  function sha256(input) {
29
53
  return createHash("sha256").update(input).digest("hex");
30
54
  }
@@ -169,7 +193,7 @@ export class OAuthAuthorize extends Resource {
169
193
  const clientId = url.searchParams.get("client_id") ?? "";
170
194
  const redirectUri = url.searchParams.get("redirect_uri") ?? "";
171
195
  const responseType = url.searchParams.get("response_type") ?? "";
172
- const scope = url.searchParams.get("scope") ?? "memory:read";
196
+ const scope = (url.searchParams.get("scope") ?? "").trim() || "memory:read";
173
197
  const state = url.searchParams.get("state") ?? "";
174
198
  const codeChallenge = url.searchParams.get("code_challenge") ?? "";
175
199
  const codeChallengeMethod = url.searchParams.get("code_challenge_method") ?? "";
@@ -183,6 +207,23 @@ export class OAuthAuthorize extends Resource {
183
207
  status: 400, headers: { "content-type": "application/json" },
184
208
  });
185
209
  }
210
+ // `state` is an opaque passthrough: printable ASCII, bounded. Anything else
211
+ // is refused (400) BEFORE rendering, so it can never reach the page.
212
+ if (!isOpaqueState(state)) {
213
+ return new Response(JSON.stringify({
214
+ error: "invalid_request",
215
+ error_description: `state must be printable ASCII of at most ${STATE_MAX_LENGTH} characters`,
216
+ }), { status: 400, headers: { "content-type": "application/json" } });
217
+ }
218
+ // Every requested scope must be one the server advertises (RFC 6749
219
+ // §4.1.2.1: invalid_scope).
220
+ const scopeTokens = scope.split(/\s+/).filter(Boolean);
221
+ if (scopeTokens.some((s) => !SUPPORTED_SCOPES.has(s))) {
222
+ return new Response(JSON.stringify({
223
+ error: "invalid_scope",
224
+ error_description: "one or more requested scopes are not supported by this server",
225
+ }), { status: 400, headers: { "content-type": "application/json" } });
226
+ }
186
227
  // Verify client exists
187
228
  const client = await databases.flair.OAuthClient.get(clientId);
188
229
  if (!client) {
@@ -190,7 +231,9 @@ export class OAuthAuthorize extends Resource {
190
231
  status: 400, headers: { "content-type": "application/json" },
191
232
  });
192
233
  }
193
- // Server-rendered consent page (minimal HTML, no JS frameworks)
234
+ // Server-rendered consent page (minimal HTML, no JS frameworks). EVERY
235
+ // interpolated value passes through `esc` — correct for element text and
236
+ // for the double-quoted attribute values below.
194
237
  const html = `<!DOCTYPE html>
195
238
  <html><head><title>Flair — Authorize</title>
196
239
  <style>body{font-family:system-ui;max-width:480px;margin:60px auto;padding:0 20px}
@@ -198,22 +241,30 @@ h1{font-size:1.4em}button{padding:10px 24px;font-size:1em;border:none;border-rad
198
241
  .approve{background:#2563eb;color:#fff}.deny{background:#e5e7eb;color:#333}
199
242
  .scope{background:#f3f4f6;padding:8px 12px;border-radius:4px;margin:4px 0;font-family:monospace}</style></head>
200
243
  <body>
201
- <h1>Authorize ${client.name || clientId}</h1>
244
+ <h1>Authorize ${esc(client.name || clientId)}</h1>
202
245
  <p>This application wants to access your Flair memories:</p>
203
- ${scope.split(" ").map((s) => `<div class="scope">${s}</div>`).join("")}
246
+ ${scopeTokens.map((s) => `<div class="scope">${esc(s)}</div>`).join("")}
204
247
  <form method="POST" action="/OAuthAuthorize" style="margin-top:24px">
205
- <input type="hidden" name="client_id" value="${clientId}">
206
- <input type="hidden" name="redirect_uri" value="${redirectUri || ALLOWED_REDIRECT_URI}">
207
- <input type="hidden" name="scope" value="${scope}">
208
- <input type="hidden" name="state" value="${state}">
209
- <input type="hidden" name="code_challenge" value="${codeChallenge}">
210
- <input type="hidden" name="code_challenge_method" value="${codeChallengeMethod}">
248
+ <input type="hidden" name="client_id" value="${esc(clientId)}">
249
+ <input type="hidden" name="redirect_uri" value="${esc(redirectUri || ALLOWED_REDIRECT_URI)}">
250
+ <input type="hidden" name="scope" value="${esc(scope)}">
251
+ <input type="hidden" name="state" value="${esc(state)}">
252
+ <input type="hidden" name="code_challenge" value="${esc(codeChallenge)}">
253
+ <input type="hidden" name="code_challenge_method" value="${esc(codeChallengeMethod)}">
211
254
  <button type="submit" name="action" value="approve" class="approve">Approve</button>
212
255
  <button type="submit" name="action" value="deny" class="deny">Deny</button>
213
256
  </form></body></html>`;
214
257
  return new Response(html, {
215
258
  status: 200,
216
- headers: { "content-type": "text/html; charset=utf-8" },
259
+ headers: {
260
+ "content-type": "text/html; charset=utf-8",
261
+ // No script is needed by this page; an inline <style> is the only
262
+ // non-default allowance. The form posts back here and the POST answers
263
+ // with a 302 to the pinned callback, so that origin must be allowed too.
264
+ // Nothing may frame the consent page.
265
+ "content-security-policy": `default-src 'none'; frame-ancestors 'none'; style-src 'unsafe-inline'; form-action 'self' ${ALLOWED_REDIRECT_ORIGIN}`,
266
+ "x-content-type-options": "nosniff",
267
+ },
217
268
  });
218
269
  }
219
270
  async post(data) {