@anthusai/papyrus 5.41.5 → 5.41.6

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.
@@ -1,8 +1,7 @@
1
1
  "use client";
2
2
 
3
+ import { Hub } from "aws-amplify/utils";
3
4
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
- import { connectNewsroomChat } from "../lib/newsroom-chat-client";
5
- import { loadProspectusAccountState, selectProspectusAccount, type ProspectusAccountState } from "../lib/prospectus-account-client";
6
5
  import { PapyrusConsoleConversation, type ConsoleConversationMessage } from "./papyrus-console-conversation";
7
6
  import {
8
7
  listPapyrusPrivateChatMessages,
@@ -30,9 +29,6 @@ function failureMessage(error: unknown): string {
30
29
  export function PapyrusPrivateChatPanel({ onClose }: { onClose: () => void }) {
31
30
  const [channel, setChannel] = useState<PapyrusPrivateChatChannel | null>(null);
32
31
  const [messages, setMessages] = useState<PapyrusPrivateChatMessage[]>([]);
33
- const [accountState, setAccountState] = useState<ProspectusAccountState | null>(null);
34
- const [connecting, setConnecting] = useState(false);
35
- const [connectionNotice, setConnectionNotice] = useState<string | null>(null);
36
32
  const [loading, setLoading] = useState(true);
37
33
  const [sending, setSending] = useState(false);
38
34
  const [error, setError] = useState<string | null>(null);
@@ -55,18 +51,13 @@ export function PapyrusPrivateChatPanel({ onClose }: { onClose: () => void }) {
55
51
  const handleFailure = useCallback(async (nextError: unknown) => {
56
52
  const failure = failureMessage(nextError);
57
53
  setError(failure);
58
- if (["sign_in_required", "chat_identity_connection_required", "publishing_account_required", "chat_account_access_denied"].includes(failure)) {
59
- const generation = ++identityGeneration.current;
54
+ if (["sign_in_required", "chat_account_access_denied"].includes(failure)) {
55
+ ++identityGeneration.current;
60
56
  setChannel(null);
61
57
  setMessages([]);
62
- setAccountState(null);
63
58
  retryAttempt.current = null;
64
59
  setSending(false);
65
60
  setLoading(false);
66
- if (failure === "publishing_account_required") {
67
- const state = await loadProspectusAccountState(window.location.pathname);
68
- if (generation === identityGeneration.current) setAccountState(state);
69
- }
70
61
  }
71
62
  }, []);
72
63
 
@@ -81,6 +72,8 @@ export function PapyrusPrivateChatPanel({ onClose }: { onClose: () => void }) {
81
72
  setError(null);
82
73
  setChannel(null);
83
74
  setMessages([]);
75
+ retryAttempt.current = null;
76
+ setSending(false);
84
77
  try {
85
78
  const nextChannel = await openPapyrusPrivateChat();
86
79
  if (generation !== identityGeneration.current) return;
@@ -94,14 +87,18 @@ export function PapyrusPrivateChatPanel({ onClose }: { onClose: () => void }) {
94
87
  }, [handleFailure, refreshMessages]);
95
88
 
96
89
  useEffect(() => {
97
- const code = new URLSearchParams(window.location.search).get("sign_in_error");
98
- if (code) setConnectionNotice(code === "newsroom_identity_mismatch"
99
- ? "The selected Google account did not match your newsroom session. Connect again with the same account."
100
- : "The publishing-account connection did not complete. You can safely try again.");
101
90
  void openConversation();
102
91
  return () => { identityGeneration.current += 1; };
103
92
  }, [openConversation]);
104
93
 
94
+ useEffect(() => Hub.listen("auth", ({ payload }) => {
95
+ if (payload.event === "tokenRefresh") {
96
+ void openConversation();
97
+ } else if (["signedOut", "signedIn", "tokenRefresh_failure"].includes(payload.event)) {
98
+ void handleFailure(new Error("sign_in_required"));
99
+ }
100
+ }), [handleFailure, openConversation]);
101
+
105
102
  useEffect(() => {
106
103
  if (!channel || !isWaitingForReply) return;
107
104
  let active = true;
@@ -146,54 +143,16 @@ export function PapyrusPrivateChatPanel({ onClose }: { onClose: () => void }) {
146
143
  }
147
144
  }, [channel, handleFailure, sending]);
148
145
 
149
- const connect = async () => {
150
- setConnecting(true);
151
- try {
152
- const returnUrl = new URL(window.location.href);
153
- returnUrl.searchParams.delete("sign_in_error");
154
- const target = await connectNewsroomChat(`${returnUrl.pathname}${returnUrl.search}${returnUrl.hash}`);
155
- window.location.assign(target);
156
- } catch (nextError) {
157
- setError(failureMessage(nextError));
158
- setConnecting(false);
159
- }
160
- };
161
- const chooseAccount = async (accountId: string) => {
162
- setConnecting(true);
163
- try {
164
- const result = await selectProspectusAccount(accountId);
165
- if ("error" in result) { setError(result.error); return; }
166
- setAccountState(null);
167
- await openConversation();
168
- } catch (nextError) { setError(failureMessage(nextError)); }
169
- finally { setConnecting(false); }
170
- };
171
-
172
146
  return <div className="papyrus-console__panel">
173
147
  <header className="papyrus-console__header">
174
148
  <p className="papyrus-console__header-label">Private chat</p>
175
149
  <button className="papyrus-console__close" onClick={onClose} type="button" aria-label="Close console">×</button>
176
150
  </header>
177
- {channel ? <p className="papyrus-console__empty" role="status">Private conversation for your selected Account.</p> : null}
151
+ {channel ? <p className="papyrus-console__empty" role="status">Private conversation for this newsroom.</p> : null}
178
152
  {!channel && !loading ? <div className="papyrus-console__access" role="alert">
179
- {error === "chat_identity_connection_required" ? <>
180
- <strong>Connect your publishing account</strong>
181
- {connectionNotice ? <span>{connectionNotice}</span> : null}
182
- <span>Continue with the same Google account you use in the newsroom, then choose the Account for this private conversation.</span>
183
- <button className="papyrus-console__new-session" disabled={connecting} onClick={() => void connect()} type="button">{connecting ? "Connecting…" : "Connect publishing account"}</button>
184
- </> : accountState?.status === "signedIn" ? <>
185
- <strong>{accountState.publishingAccounts.length === 0 ? "Chat access is unavailable" : "Choose your publishing Account"}</strong>
186
- {accountState.publishingAccounts.length === 0 ? <>
187
- <span>None of your Accounts is enabled for this publication. Publication setup must be resolved before you can chat.</span>
188
- <span>You can return to the newsroom while this is resolved. Check again after access has been corrected.</span>
189
- <button className="papyrus-console__new-session" onClick={() => void openConversation()} type="button">Check again</button>
190
- </> : accountState.publishingAccounts.map(account => <button className="papyrus-console__new-session" disabled={connecting} key={account.accountId} onClick={() => void chooseAccount(account.accountId)} type="button">{account.name ?? account.accountId}</button>)}
191
- {error !== "publishing_account_required" ? <span>{error}</span> : null}
192
- </> : <>
193
- <strong>Private chat could not be opened.</strong>
194
- <span>{error === "sign_in_required" ? "Your newsroom session has expired. Return to the newsroom and sign in from the account menu, then retry." : error === "chat_account_access_denied" ? "Your access to this conversation has changed. Retry to check your current access." : error === "publishing_account_required" ? "Publishing Account access could not be checked. Retry when your connection is available." : error}</span>
195
- <button className="papyrus-console__new-session" onClick={() => void openConversation()} type="button">Retry</button>
196
- </>}
153
+ <strong>Private chat could not be opened.</strong>
154
+ <span>{error === "sign_in_required" ? "Your newsroom session has expired. Return to the newsroom and sign in from the account menu, then retry." : error === "chat_account_access_denied" ? "Your access to this conversation has changed. Retry to check your current access." : error}</span>
155
+ <button className="papyrus-console__new-session" onClick={() => void openConversation()} type="button">Retry</button>
197
156
  <button className="papyrus-console__new-session" onClick={onClose} type="button">Back to newsroom</button>
198
157
  </div> : <PapyrusConsoleConversation
199
158
  messages={conversationMessages}
@@ -202,7 +161,7 @@ export function PapyrusPrivateChatPanel({ onClose }: { onClose: () => void }) {
202
161
  onSendMessage={sendMessage}
203
162
  error={error}
204
163
  emptyState={loading ? <p className="papyrus-console__empty">Opening private conversation…</p> : (
205
- <p className="papyrus-console__empty">This conversation is private to your selected Account and editor session.</p>
164
+ <p className="papyrus-console__empty">This conversation is private to you in this newsroom.</p>
206
165
  )}
207
166
  />}
208
167
  </div>;
@@ -3,7 +3,7 @@ import type { JwksCache } from "aws-jwt-verify/jwk";
3
3
  import type { NextRequest } from "next/server";
4
4
  import { readAmplifyOutputsFile } from "./amplify-outputs-path";
5
5
 
6
- export type NewsroomChatIdentity = { subject: string };
6
+ export type NewsroomChatIdentity = { subject: string; issuer: string; clientId: string; expiresAt: number };
7
7
  export type NewsroomChatIdentityResolver = (request: NextRequest) => Promise<NewsroomChatIdentity | null>;
8
8
 
9
9
  export function newsroomChatIdentityResolver(
@@ -21,7 +21,7 @@ export function newsroomChatIdentityResolver(
21
21
  if (!token) return null;
22
22
  try {
23
23
  const claims = await verifier.verify(token);
24
- return { subject: claims.sub };
24
+ return { subject: claims.sub, issuer: claims.iss, clientId: auth.user_pool_client_id, expiresAt: claims.exp };
25
25
  } catch {
26
26
  return null;
27
27
  }
@@ -2,52 +2,35 @@ import { resolveNewsroomChatIdentity, type NewsroomChatIdentityResolver } from "
2
2
  import { createHash } from "node:crypto";
3
3
  import type { EmbeddedChatAppDependencies } from "chatticus/chat-server";
4
4
  import type { NextRequest } from "next/server";
5
- import {
6
- ProspectusAccountsError,
7
- authorizeSignedInPersonForAccount,
8
- } from "./prospectus-site-identity";
9
- import {
10
- resolveProspectusSignInRuntime,
11
- signedInProspectusSession,
12
- type ProspectusSignInRuntime,
13
- } from "./prospectus-session";
14
- import { prospectusSiteProduct, publishingAccountsForSite } from "./prospectus-publication-access";
15
5
  import { publicSiteOrigin } from "./site-origin-value";
16
6
 
17
7
  const NO_STORE_HEADERS = { "cache-control": "no-store" };
18
8
 
19
9
  export interface PapyrusChatScope {
20
- siteProduct: string;
21
- accountId: string;
22
- personId: string;
23
10
  tenantId: string;
24
11
  editorId: string;
25
12
  }
26
13
 
27
14
  export interface PapyrusHostedChatOptions {
28
15
  resolveNewsroomIdentity?: NewsroomChatIdentityResolver;
29
- resolveRuntime?: (siteOrigin: string) => Promise<ProspectusSignInRuntime | null>;
30
16
  resolvePrivateDependencies?: () => Promise<EmbeddedChatAppDependencies | null>;
31
17
  privateChatEnabled?: boolean;
32
- siteProduct?: string | null;
33
18
  environment?: Record<string, string | undefined>;
34
19
  nowInSeconds?: () => number;
35
20
  }
36
21
 
37
- function siteAndAccountKey(siteProduct: string, accountId: string): string {
38
- return createHash("sha256").update(JSON.stringify([siteProduct, accountId])).digest("hex");
22
+ /** A new namespace: never aliases Account-scoped or legacy transcripts. */
23
+ export function derivePapyrusChatScope(publicationNamespace: string, issuer: string, subject: string): PapyrusChatScope {
24
+ const tenantHash = createHash("sha256").update(JSON.stringify(["newsroom-v1", publicationNamespace, issuer])).digest("hex");
25
+ const editorHash = createHash("sha256").update(JSON.stringify(["newsroom-v1", publicationNamespace, issuer, subject])).digest("hex");
26
+ return { tenantId: `papyrus-newsroom-v1-${tenantHash.slice(0, 40)}`, editorId: `papyrus-newsroom-editor-v1-${editorHash.slice(0, 40)}` };
39
27
  }
40
28
 
41
- export function derivePapyrusChatScope(siteProduct: string, accountId: string, personId: string): PapyrusChatScope {
42
- const tenantHash = siteAndAccountKey(siteProduct, accountId);
43
- const editorHash = createHash("sha256").update(JSON.stringify([siteProduct, accountId, personId])).digest("hex");
44
- return {
45
- siteProduct,
46
- personId,
47
- accountId,
48
- tenantId: `papyrus-${tenantHash.slice(0, 40)}`,
49
- editorId: `papyrus-editor-${editorHash.slice(0, 40)}`,
50
- };
29
+ /** Existing server storage resources bind the publication, independently of request hosts or claims. */
30
+ function publicationNamespace(environment: Record<string, string | undefined>, clientId: string): string | null {
31
+ const bucket = environment.PAPYRUS_CHAT_SESSION_BUCKET?.trim();
32
+ const table = environment.PAPYRUS_CHAT_MESSAGING_TABLE?.trim();
33
+ return bucket && table ? JSON.stringify([bucket, table, clientId]) : null;
51
34
  }
52
35
 
53
36
  type ResolvedPapyrusPrincipal = {
@@ -61,71 +44,24 @@ type ResolvedPapyrusPrincipal = {
61
44
 
62
45
  async function principalForRequest(
63
46
  request: NextRequest,
64
- operation: "console:read" | "console:write",
65
47
  options: PapyrusHostedChatOptions,
66
- ): Promise<{ principal: ResolvedPapyrusPrincipal | null; status: number; error?: string }> {
67
- const environment = options.environment ?? process.env;
68
- const siteProduct = options.siteProduct !== undefined ? options.siteProduct : prospectusSiteProduct(environment);
69
- if (!siteProduct) return { principal: null, status: 503 };
70
-
71
- let runtime: ProspectusSignInRuntime | null;
72
- try {
73
- runtime = await (options.resolveRuntime ?? resolveProspectusSignInRuntime)(publicSiteOrigin(request, environment));
74
- } catch {
75
- return { principal: null, status: 503 };
76
- }
77
- if (!runtime) return { principal: null, status: 503 };
78
-
79
- let newsroomIdentity;
48
+ ): Promise<{ principal: ResolvedPapyrusPrincipal | null; status: number; expiresAt?: number }> {
49
+ let identity;
80
50
  try {
81
- newsroomIdentity = await (options.resolveNewsroomIdentity ?? resolveNewsroomChatIdentity)(request);
51
+ identity = await (options.resolveNewsroomIdentity ?? resolveNewsroomChatIdentity)(request);
82
52
  } catch {
83
53
  return { principal: null, status: 503 };
84
54
  }
85
- if (!newsroomIdentity) return { principal: null, status: 401 };
86
- const nowInSeconds = options.nowInSeconds?.() ?? Math.floor(Date.now() / 1000);
87
- const session = signedInProspectusSession(request, runtime.sealingSecret, nowInSeconds);
88
- if (!session || !Number.isFinite(session.accessTokenExpiresAt) || session.accessTokenExpiresAt <= nowInSeconds) {
89
- return { principal: null, status: 409, error: "chat_identity_connection_required" };
90
- }
91
- if (session.newsroomSubject !== newsroomIdentity.subject) {
92
- return { principal: null, status: 409, error: "chat_identity_connection_required" };
93
- }
94
- if (!session.selectedAccountId) return { principal: null, status: 409, error: "publishing_account_required" };
95
-
96
- try {
97
- const directory = await runtime.accounts.accountDirectory(session.accessToken);
98
- if (directory.person?.id !== session.personId) return { principal: null, status: 401 };
99
- if (!publishingAccountsForSite(directory.accounts, siteProduct).some((account) => account.accountId === session.selectedAccountId)) {
100
- return { principal: null, status: 403 };
101
- }
102
- const authorization = await authorizeSignedInPersonForAccount(
103
- runtime.accounts,
104
- session.accessToken,
105
- session.selectedAccountId,
106
- operation,
107
- );
108
- if (authorization.personId !== session.personId || authorization.accountId !== session.selectedAccountId || authorization.operation !== operation) {
109
- return { principal: null, status: 403 };
110
- }
111
- const scope = derivePapyrusChatScope(siteProduct, session.selectedAccountId, session.personId);
112
- return {
113
- principal: {
114
- kind: "user",
115
- tenantId: scope.tenantId,
116
- userId: scope.editorId,
117
- workerId: null,
118
- organizationStatus: "enabled",
119
- role: "member",
120
- },
121
- status: 200,
122
- };
123
- } catch (error) {
124
- if (error instanceof ProspectusAccountsError && (error.status === 401 || error.status === 403)) {
125
- return { principal: null, status: error.status };
126
- }
127
- return { principal: null, status: 503 };
128
- }
55
+ const now = options.nowInSeconds?.() ?? Math.floor(Date.now() / 1000);
56
+ if (!identity || !identity.subject || !identity.issuer || !identity.clientId || !Number.isFinite(identity.expiresAt) || identity.expiresAt <= now) return { principal: null, status: 401 };
57
+ const namespace = publicationNamespace(options.environment ?? process.env, identity.clientId);
58
+ if (!namespace) return { principal: null, status: 503 };
59
+ const scope = derivePapyrusChatScope(namespace, identity.issuer, identity.subject);
60
+ return {
61
+ principal: { kind: "user", tenantId: scope.tenantId, userId: scope.editorId, workerId: null, organizationStatus: "enabled", role: "member" },
62
+ status: 200,
63
+ expiresAt: identity.expiresAt,
64
+ };
129
65
  }
130
66
 
131
67
  function jsonFailure(status: number, error: string): Response {
@@ -175,8 +111,8 @@ export async function handlePapyrusHostedChatRequest(
175
111
  const privateChatEnabled = options.privateChatEnabled ?? environment.PAPYRUS_PRIVATE_CHAT_ENABLED === "true";
176
112
  if (!privateChatEnabled) return jsonFailure(404, "private_chat_disabled");
177
113
 
178
- const authorization = await principalForRequest(request, request.method === "POST" ? "console:write" : "console:read", options);
179
- if (!authorization.principal) return jsonFailure(authorization.status, authorization.error ?? (authorization.status === 401 ? "sign_in_required" : authorization.status === 403 ? "chat_account_access_denied" : "chat_runtime_unavailable"));
114
+ const authorization = await principalForRequest(request, options);
115
+ if (!authorization.principal) return jsonFailure(authorization.status, (authorization.status === 401 ? "sign_in_required" : authorization.status === 403 ? "chat_account_access_denied" : "chat_runtime_unavailable"));
180
116
 
181
117
  let dependencies: EmbeddedChatAppDependencies | null;
182
118
  try {
@@ -226,5 +162,38 @@ export async function handlePapyrusHostedChatRequest(
226
162
  ...dependencies,
227
163
  resolvePrincipal: async () => authorization.principal,
228
164
  });
229
- return app.fetch(forwarded);
165
+ const response = await app.fetch(forwarded);
166
+ if (path[0] !== "turns" || path[2] !== "stream" || !response.ok || !response.body) return response;
167
+ const remaining = (authorization.expiresAt! - (options.nowInSeconds?.() ?? Date.now() / 1000)) * 1000;
168
+ return expireChatStream(response, remaining);
169
+ }
170
+
171
+ /** End an established stream at JWT expiry; reconnect must pass current authorization again. */
172
+ export function expireChatStream(response: Response, remainingMilliseconds: number): Response {
173
+ if (!response.body) return response;
174
+ const reader = response.body.getReader();
175
+ let closed = false;
176
+ let timer: ReturnType<typeof setTimeout>;
177
+ const body = new ReadableStream<Uint8Array>({
178
+ start(controller) {
179
+ timer = setTimeout(() => {
180
+ if (closed) return;
181
+ closed = true;
182
+ controller.close();
183
+ void reader.cancel().catch(() => {});
184
+ }, Math.max(0, Math.min(remainingMilliseconds, 2_147_483_647)));
185
+ },
186
+ async pull(controller) {
187
+ try {
188
+ const next = await reader.read();
189
+ if (closed) return;
190
+ if (next.done) { closed = true; clearTimeout(timer); controller.close(); }
191
+ else controller.enqueue(next.value);
192
+ } catch (error) {
193
+ if (!closed) { closed = true; clearTimeout(timer); controller.error(error); }
194
+ }
195
+ },
196
+ async cancel(reason) { closed = true; clearTimeout(timer); await reader.cancel(reason); },
197
+ });
198
+ return new Response(body, { status: response.status, headers: response.headers });
230
199
  }
@@ -31,6 +31,8 @@ async function requestJson<T>(path: string, init: RequestInit, fetcher: PapyrusP
31
31
  });
32
32
  const payload = await response.json().catch(() => null) as Record<string, unknown> | null;
33
33
  if (!response.ok) {
34
+ if (response.status === 401) throw new Error("sign_in_required");
35
+ if (response.status === 403) throw new Error("chat_account_access_denied");
34
36
  const error = typeof payload?.error === "string" ? payload.error
35
37
  : typeof payload?.detail === "string" ? payload.detail
36
38
  : `Private chat request failed (${response.status}).`;
@@ -40,7 +42,7 @@ async function requestJson<T>(path: string, init: RequestInit, fetcher: PapyrusP
40
42
  return payload as T;
41
43
  }
42
44
 
43
- /** Open the current editor's server-derived private channel using the verified newsroom identity and connected account session. */
45
+ /** Open the current editor's server-derived private channel using the verified publication-local newsroom identity. */
44
46
  export async function openPapyrusPrivateChat(fetcher: PapyrusPrivateChatFetch = newsroomChatFetch): Promise<PapyrusPrivateChatChannel> {
45
47
  const result = await requestJson<PapyrusPrivateChatChannel>("private-channel", { method: "POST" }, fetcher);
46
48
  if (!result.channel_id?.trim() || !Array.isArray(result.participants)) {
package/package.json CHANGED
@@ -461,7 +461,7 @@
461
461
  "optional": true
462
462
  }
463
463
  },
464
- "version": "5.41.5",
464
+ "version": "5.41.6",
465
465
  "dependencies": {
466
466
  "@aws-amplify/adapter-nextjs": "^1.7.3",
467
467
  "@aws-crypto/sha256-js": "5.2.0",
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "5.41.5",
2
+ "version": "5.41.6",
3
3
  "routes": [
4
4
  {
5
5
  "file": "app/%5F_preview/[[...path]]/route.ts",