@tangle-network/agent-app 0.50.26 → 0.50.28
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/chat-routes/index.js +4 -4
- package/dist/{chunk-EA3GB7F4.js → chunk-KTV5RQBQ.js} +4 -4
- package/dist/{chunk-6UBRYSED.js → chunk-QWYAR2CY.js} +2 -2
- package/dist/{chunk-VC3N3RZU.js → chunk-RFVTTZPG.js} +2 -2
- package/dist/{chunk-VC3N3RZU.js.map → chunk-RFVTTZPG.js.map} +1 -1
- package/dist/{chunk-EX2XVDPE.js → chunk-TJCTC5QI.js} +2 -2
- package/dist/hosted-agent/application-verification.d.ts +26 -0
- package/dist/hosted-agent/application.d.ts +3 -0
- package/dist/hosted-agent/application.js +33 -7
- package/dist/hosted-agent/application.js.map +1 -1
- package/dist/hosted-agent/react/ApplicationLineSetup.d.ts +10 -3
- package/dist/hosted-agent/react/LineSetup.d.ts +1 -1
- package/dist/hosted-agent/react/contracts.d.ts +9 -0
- package/dist/hosted-agent/react/index.d.ts +1 -1
- package/dist/hosted-agent/react/index.js +202 -72
- package/dist/hosted-agent/react/index.js.map +1 -1
- package/dist/hosted-agent/react/lines.css +14 -4
- package/dist/hosted-agent/workspace-line.d.ts +9 -2
- package/dist/preset-cloudflare/index.js +2 -2
- package/dist/sandbox/index.js +4 -4
- package/dist/tools/index.js +4 -4
- package/dist/work-product/index.js +30 -18
- package/dist/work-product/index.js.map +1 -1
- package/dist/work-product/route.d.ts +4 -2
- package/dist/work-product/service.d.ts +2 -0
- package/package.json +11 -11
- /package/dist/{chunk-EA3GB7F4.js.map → chunk-KTV5RQBQ.js.map} +0 -0
- /package/dist/{chunk-6UBRYSED.js.map → chunk-QWYAR2CY.js.map} +0 -0
- /package/dist/{chunk-EX2XVDPE.js.map → chunk-TJCTC5QI.js.map} +0 -0
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
OPENUI_NODE_JSON_SCHEMA,
|
|
6
6
|
OPENUI_NODE_TYPES
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-RFVTTZPG.js";
|
|
8
8
|
|
|
9
9
|
// src/tools/openai.ts
|
|
10
10
|
var APP_TOOL_NAMES = ["submit_proposal", "schedule_followup", "render_ui", "add_citation"];
|
|
@@ -112,4 +112,4 @@ export {
|
|
|
112
112
|
customToolToOpenAI,
|
|
113
113
|
findCustomTool
|
|
114
114
|
};
|
|
115
|
-
//# sourceMappingURL=chunk-
|
|
115
|
+
//# sourceMappingURL=chunk-TJCTC5QI.js.map
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Public TEST data. The private CONFIRM reply is never returned to a browser. */
|
|
2
|
+
export interface ApplicationSenderVerificationStart {
|
|
3
|
+
lineId: string;
|
|
4
|
+
testId: string;
|
|
5
|
+
state: 'awaiting_test';
|
|
6
|
+
testText: string;
|
|
7
|
+
expiresAt: string;
|
|
8
|
+
}
|
|
9
|
+
/** Browser-safe status from the owner server. No sender address is present. */
|
|
10
|
+
export interface ApplicationSenderVerification {
|
|
11
|
+
lineId: string;
|
|
12
|
+
testId: string;
|
|
13
|
+
state: 'awaiting_test' | 'sending' | 'challenge_sent' | 'verified' | 'consumed' | 'cancelled' | 'superseded' | 'failed' | 'expired';
|
|
14
|
+
expiresAt: string;
|
|
15
|
+
proof: {
|
|
16
|
+
signedInboundTestAt: string | null;
|
|
17
|
+
providerReplyAcknowledgedAt: string | null;
|
|
18
|
+
signedInboundConfirmAt: string | null;
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
/** The owner-key SDK read includes the confirmed sender for the attach helper. */
|
|
22
|
+
export interface OwnerApplicationSenderVerification extends ApplicationSenderVerification {
|
|
23
|
+
approvedSender?: string;
|
|
24
|
+
}
|
|
25
|
+
/** Use at the host response boundary so approvedSender cannot enter page state. */
|
|
26
|
+
export declare function publicApplicationSenderVerification(result: OwnerApplicationSenderVerification): ApplicationSenderVerification;
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { type LineApplicationRequest, type LineApplicationState } from '@tangle-network/sandbox/core';
|
|
2
2
|
export { attachWorkspaceLine } from './workspace-line';
|
|
3
|
+
export { publicApplicationSenderVerification } from './application-verification';
|
|
4
|
+
export type { ApplicationOwnerLines } from './workspace-line';
|
|
5
|
+
export type { ApplicationSenderVerification, ApplicationSenderVerificationStart, OwnerApplicationSenderVerification } from './application-verification';
|
|
3
6
|
/** Missing is an affirmative storage observation, never an error fallback. */
|
|
4
7
|
export type ApplicationLineObservation = LineApplicationState | {
|
|
5
8
|
state: 'missing';
|
|
@@ -12,10 +12,18 @@ import {
|
|
|
12
12
|
|
|
13
13
|
// src/hosted-agent/workspace-line.ts
|
|
14
14
|
async function attachWorkspaceLine(input) {
|
|
15
|
-
|
|
15
|
+
if (!/^lsv_[A-Za-z0-9_-]+$/.test(input.senderVerificationId)) {
|
|
16
|
+
throw new TypeError("A valid sender verification id is required");
|
|
17
|
+
}
|
|
18
|
+
const verification = await input.ownerLines.getSenderVerification(input.lineId, input.senderVerificationId);
|
|
19
|
+
const expiresAt = new Date(verification.expiresAt).getTime();
|
|
20
|
+
if (verification.lineId !== input.lineId || verification.testId !== input.senderVerificationId || verification.state !== "verified" || !verification.proof.signedInboundTestAt || !verification.proof.providerReplyAcknowledgedAt || !verification.proof.signedInboundConfirmAt || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) {
|
|
21
|
+
throw new TypeError("The selected line has no current verified sender proof");
|
|
22
|
+
}
|
|
23
|
+
const address = verification.approvedSender?.trim() ?? "";
|
|
16
24
|
const turnsPerDay = input.turnsPerDay ?? 20;
|
|
17
|
-
if (!/^\+[1-9]\d{6,14}$/.test(address)
|
|
18
|
-
throw new TypeError("The
|
|
25
|
+
if (!/^\+[1-9]\d{6,14}$/.test(address)) {
|
|
26
|
+
throw new TypeError("The verified sender must be an E.164 phone number");
|
|
19
27
|
}
|
|
20
28
|
if (!Number.isSafeInteger(turnsPerDay) || turnsPerDay < 1 || turnsPerDay > 1e4) {
|
|
21
29
|
throw new TypeError("A daily turn limit between 1 and 10000 is required");
|
|
@@ -27,15 +35,32 @@ async function attachWorkspaceLine(input) {
|
|
|
27
35
|
if (!/^[\x21-\x7e]{1,1024}$/.test(input.application.binding) || !/^[\x21-\x7e]{16,512}$/.test(input.application.secret)) {
|
|
28
36
|
throw new TypeError("A binding and a header-safe callback credential are required");
|
|
29
37
|
}
|
|
30
|
-
|
|
38
|
+
const attachment = {
|
|
31
39
|
number: input.lineId,
|
|
40
|
+
senderVerificationId: input.senderVerificationId,
|
|
32
41
|
mode: "personal",
|
|
33
|
-
members: [{ address
|
|
42
|
+
members: [{ address, role: "owner" }],
|
|
34
43
|
unknownSenders: "reject",
|
|
35
44
|
roles: { owner: { context: "own", tools: "act" } },
|
|
36
45
|
respond: { kind: "agent", application: { ...input.application } },
|
|
37
46
|
limits: { turnsPerMemberPerDay: turnsPerDay }
|
|
38
|
-
}
|
|
47
|
+
};
|
|
48
|
+
return input.box.lines.attach(attachment);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/hosted-agent/application-verification.ts
|
|
52
|
+
function publicApplicationSenderVerification(result) {
|
|
53
|
+
return {
|
|
54
|
+
lineId: result.lineId,
|
|
55
|
+
testId: result.testId,
|
|
56
|
+
state: result.state,
|
|
57
|
+
expiresAt: result.expiresAt,
|
|
58
|
+
proof: {
|
|
59
|
+
signedInboundTestAt: result.proof.signedInboundTestAt,
|
|
60
|
+
providerReplyAcknowledgedAt: result.proof.providerReplyAcknowledgedAt,
|
|
61
|
+
signedInboundConfirmAt: result.proof.signedInboundConfirmAt
|
|
62
|
+
}
|
|
63
|
+
};
|
|
39
64
|
}
|
|
40
65
|
|
|
41
66
|
// src/hosted-agent/application.ts
|
|
@@ -93,6 +118,7 @@ function failure(status, code) {
|
|
|
93
118
|
}
|
|
94
119
|
export {
|
|
95
120
|
attachWorkspaceLine,
|
|
96
|
-
createApplicationLineHandler
|
|
121
|
+
createApplicationLineHandler,
|
|
122
|
+
publicApplicationSenderVerification
|
|
97
123
|
};
|
|
98
124
|
//# sourceMappingURL=application.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hosted-agent/application.ts","../../src/hosted-agent/workspace-line.ts"],"sourcesContent":["import { parseJsonObjectBody } from '../web/core'\nimport {\n LINE_APPLICATION_REQUEST_MAX_BYTES,\n parseLineApplicationRequest,\n parseLineApplicationResult,\n type LineApplicationRequest,\n type LineApplicationResult,\n type LineApplicationState,\n} from '@tangle-network/sandbox/core'\n\nexport { attachWorkspaceLine } from './workspace-line'\n\n/** Missing is an affirmative storage observation, never an error fallback. */\nexport type ApplicationLineObservation = LineApplicationState | { state: 'missing' }\n\nexport interface ApplicationLineOptions<T> {\n /** Authenticate before consuming the body. It must not trust model-supplied identity. */\n authenticate(request: Request): Promise<{ binding: string; target: T }>\n /** Recheck live binding, membership, owner authority and exact retained message. */\n authorize(target: T, input: Readonly<LineApplicationRequest>): Promise<void>\n /** Observe the application's existing durable turn, transcript and outputs. */\n read(target: T, input: Readonly<LineApplicationRequest>): Promise<ApplicationLineObservation>\n /**\n * Enter the normal persisted chat route using input.messageId as its stable\n * client turn identity. That route owns admission, locks and completion.\n * This callback MUST deduplicate that identity across concurrent requests.\n */\n admit(target: T, input: Readonly<LineApplicationRequest>): Promise<void>\n}\n\n/** One bounded pass from the native Lines worker into the application's existing execution path. */\nexport function createApplicationLineHandler<T>(options: ApplicationLineOptions<T>) {\n return async (request: Request): Promise<Response> => {\n if (request.method !== 'POST') return failure(405, 'method_not_allowed')\n let authenticated: { binding: string; target: T }\n try {\n authenticated = await options.authenticate(request)\n } catch (error) {\n return error instanceof Response ? error : failure(503, 'line_authentication_unavailable')\n }\n let input: LineApplicationRequest\n try {\n if (request.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json')\n return failure(415, 'json_required')\n const [body, error] = await parseJsonObjectBody(request, { maxBytes: LINE_APPLICATION_REQUEST_MAX_BYTES })\n if (error) return error\n input = parseLineApplicationRequest(body)\n if (input.binding !== authenticated.binding) return failure(403, 'line_binding_mismatch')\n if (request.headers.get('idempotency-key') !== `line-application:${input.messageId}`)\n return failure(400, 'idempotency_key_mismatch')\n } catch {\n return failure(400, 'line_request_invalid')\n }\n // A viewer's AbortSignal must not cancel the accepted application task.\n const immutable = Object.freeze({ ...input, sender: Object.freeze({ ...input.sender }) })\n try {\n const { target } = authenticated\n await options.authorize(target, immutable)\n let observed = await options.read(target, immutable)\n if (observed.state === 'missing') {\n if (immutable.acceptedExecutionId !== undefined)\n return failure(503, 'accepted_execution_unavailable')\n // The read may yield to revocation; check again before admitting work.\n await options.authorize(target, immutable)\n await options.admit(target, immutable)\n observed = await options.read(target, immutable)\n if (observed.state === 'missing') observed = { state: 'pending', admitted: false }\n }\n // Reading or admitting work may yield to a disconnect or member revocation.\n await options.authorize(target, immutable)\n const result: LineApplicationResult = parseLineApplicationResult({\n ...observed, version: 1, binding: input.binding,\n messageId: input.messageId, attachmentId: input.attachmentId,\n }, input)\n return Response.json(result, { headers: { 'cache-control': 'no-store' } })\n } catch (error) {\n // Unavailable authoritative state is not permission to start a new task.\n return error instanceof Response ? error : failure(503, 'line_application_unavailable')\n }\n }\n}\n\nfunction failure(status: number, code: string): Response {\n return Response.json({ error: { code } }, { status, headers: { 'cache-control': 'no-store' } })\n}\n","import type { LineApplication, LineAttachment, SandboxInstance } from '@tangle-network/sandbox/core'\n\n/** A line delegates its nominated owner to the application's normal chat path. */\nexport async function attachWorkspaceLine(input: {\n box: Pick<SandboxInstance, 'lines'>\n lineId: string\n ownerAddress: string\n application: LineApplication\n turnsPerDay?: number\n}): Promise<LineAttachment> {\n const address = input.ownerAddress.trim()\n const turnsPerDay = input.turnsPerDay ?? 20\n if (!/^\\+[1-9]\\d{6,14}$/.test(address) && !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(address)) {\n throw new TypeError('The delegated sender must be an E.164 number or email/Apple ID')\n }\n if (!Number.isSafeInteger(turnsPerDay) || turnsPerDay < 1 || turnsPerDay > 10_000) {\n throw new TypeError('A daily turn limit between 1 and 10000 is required')\n }\n const url = new URL(input.application.url)\n if (url.protocol !== 'https:' || url.username || url.password || url.hash) {\n throw new TypeError('The application callback must use HTTPS without URL credentials or a fragment')\n }\n if (!/^[\\x21-\\x7e]{1,1024}$/.test(input.application.binding)\n || !/^[\\x21-\\x7e]{16,512}$/.test(input.application.secret)) {\n throw new TypeError('A binding and a header-safe callback credential are required')\n }\n return input.box.lines.attach({\n number: input.lineId,\n mode: 'personal',\n members: [{ address: address.includes('@') ? address.toLowerCase() : address, role: 'owner' }],\n unknownSenders: 'reject',\n roles: { owner: { context: 'own', tools: 'act' } },\n respond: { kind: 'agent', application: { ...input.application } },\n limits: { turnsPerMemberPerDay: turnsPerDay },\n })\n}\n"],"mappings":";;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;;;ACLP,eAAsB,oBAAoB,OAMd;AAC1B,QAAM,UAAU,MAAM,aAAa,KAAK;AACxC,QAAM,cAAc,MAAM,eAAe;AACzC,MAAI,CAAC,oBAAoB,KAAK,OAAO,KAAK,CAAC,6BAA6B,KAAK,OAAO,GAAG;AACrF,UAAM,IAAI,UAAU,gEAAgE;AAAA,EACtF;AACA,MAAI,CAAC,OAAO,cAAc,WAAW,KAAK,cAAc,KAAK,cAAc,KAAQ;AACjF,UAAM,IAAI,UAAU,oDAAoD;AAAA,EAC1E;AACA,QAAM,MAAM,IAAI,IAAI,MAAM,YAAY,GAAG;AACzC,MAAI,IAAI,aAAa,YAAY,IAAI,YAAY,IAAI,YAAY,IAAI,MAAM;AACzE,UAAM,IAAI,UAAU,+EAA+E;AAAA,EACrG;AACA,MAAI,CAAC,wBAAwB,KAAK,MAAM,YAAY,OAAO,KACtD,CAAC,wBAAwB,KAAK,MAAM,YAAY,MAAM,GAAG;AAC5D,UAAM,IAAI,UAAU,8DAA8D;AAAA,EACpF;AACA,S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AO,QAAQ,OAAO,OAAO,EAAE,GAAG,MAAM,OAAO,CAAC,EAAE,CAAC;AACxF,QAAI;AACF,YAAM,EAAE,OAAO,IAAI;AACnB,YAAM,QAAQ,UAAU,QAAQ,SAAS;AACzC,UAAI,WAAW,MAAM,QAAQ,KAAK,QAAQ,SAAS;AACnD,UAAI,SAAS,UAAU,WAAW;AAChC,YAAI,UAAU,wBAAwB;AACpC,iBAAO,QAAQ,KAAK,gCAAgC;AAEtD,cAAM,QAAQ,UAAU,QAAQ,SAAS;AACzC,cAAM,QAAQ,MAAM,QAAQ,SAAS;AACrC,mBAAW,MAAM,QAAQ,KAAK,QAAQ,SAAS;AAC/C,YAAI,SAAS,UAAU,UAAW,YAAW,EAAE,OAAO,WAAW,UAAU,MAAM;AAAA,MACnF;AAEA,YAAM,QAAQ,UAAU,QAAQ,SAAS;AACzC,YAAM,SAAgC,2BAA2B;AAAA,QAC/D,GAAG;AAAA,QAAU,SAAS;AAAA,QAAG,SAAS,MAAM;AAAA,QACxC,WAAW,MAAM;AAAA,QAAW,cAAc,MAAM;AAAA,MAClD,GAAG,KAAK;AACR,aAAO,SAAS,KAAK,QAAQ,EAAE,SAAS,EAAE,iBAAiB,WAAW,EAAE,CAAC;AAAA,IAC3E,SAAS,OAAO;AAEd,aAAO,iBAAiB,WAAW,QAAQ,QAAQ,KAAK,8BAA8B;AAAA,IACxF;AAAA,EACF;AACF;AAEA,SAAS,QAAQ,QAAgB,MAAwB;AACvD,SAAO,SAAS,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,SAAS,EAAE,iBAAiB,WAAW,EAAE,CAAC;AAChG;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/hosted-agent/application.ts","../../src/hosted-agent/workspace-line.ts","../../src/hosted-agent/application-verification.ts"],"sourcesContent":["import { parseJsonObjectBody } from '../web/core'\nimport {\n LINE_APPLICATION_REQUEST_MAX_BYTES,\n parseLineApplicationRequest,\n parseLineApplicationResult,\n type LineApplicationRequest,\n type LineApplicationResult,\n type LineApplicationState,\n} from '@tangle-network/sandbox/core'\n\nexport { attachWorkspaceLine } from './workspace-line'\nexport { publicApplicationSenderVerification } from './application-verification'\nexport type { ApplicationOwnerLines } from './workspace-line'\nexport type { ApplicationSenderVerification, ApplicationSenderVerificationStart, OwnerApplicationSenderVerification } from './application-verification'\n\n/** Missing is an affirmative storage observation, never an error fallback. */\nexport type ApplicationLineObservation = LineApplicationState | { state: 'missing' }\n\nexport interface ApplicationLineOptions<T> {\n /** Authenticate before consuming the body. It must not trust model-supplied identity. */\n authenticate(request: Request): Promise<{ binding: string; target: T }>\n /** Recheck live binding, membership, owner authority and exact retained message. */\n authorize(target: T, input: Readonly<LineApplicationRequest>): Promise<void>\n /** Observe the application's existing durable turn, transcript and outputs. */\n read(target: T, input: Readonly<LineApplicationRequest>): Promise<ApplicationLineObservation>\n /**\n * Enter the normal persisted chat route using input.messageId as its stable\n * client turn identity. That route owns admission, locks and completion.\n * This callback MUST deduplicate that identity across concurrent requests.\n */\n admit(target: T, input: Readonly<LineApplicationRequest>): Promise<void>\n}\n\n/** One bounded pass from the native Lines worker into the application's existing execution path. */\nexport function createApplicationLineHandler<T>(options: ApplicationLineOptions<T>) {\n return async (request: Request): Promise<Response> => {\n if (request.method !== 'POST') return failure(405, 'method_not_allowed')\n let authenticated: { binding: string; target: T }\n try {\n authenticated = await options.authenticate(request)\n } catch (error) {\n return error instanceof Response ? error : failure(503, 'line_authentication_unavailable')\n }\n let input: LineApplicationRequest\n try {\n if (request.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json')\n return failure(415, 'json_required')\n const [body, error] = await parseJsonObjectBody(request, { maxBytes: LINE_APPLICATION_REQUEST_MAX_BYTES })\n if (error) return error\n input = parseLineApplicationRequest(body)\n if (input.binding !== authenticated.binding) return failure(403, 'line_binding_mismatch')\n if (request.headers.get('idempotency-key') !== `line-application:${input.messageId}`)\n return failure(400, 'idempotency_key_mismatch')\n } catch {\n return failure(400, 'line_request_invalid')\n }\n // A viewer's AbortSignal must not cancel the accepted application task.\n const immutable = Object.freeze({ ...input, sender: Object.freeze({ ...input.sender }) })\n try {\n const { target } = authenticated\n await options.authorize(target, immutable)\n let observed = await options.read(target, immutable)\n if (observed.state === 'missing') {\n if (immutable.acceptedExecutionId !== undefined)\n return failure(503, 'accepted_execution_unavailable')\n // The read may yield to revocation; check again before admitting work.\n await options.authorize(target, immutable)\n await options.admit(target, immutable)\n observed = await options.read(target, immutable)\n if (observed.state === 'missing') observed = { state: 'pending', admitted: false }\n }\n // Reading or admitting work may yield to a disconnect or member revocation.\n await options.authorize(target, immutable)\n const result: LineApplicationResult = parseLineApplicationResult({\n ...observed, version: 1, binding: input.binding,\n messageId: input.messageId, attachmentId: input.attachmentId,\n }, input)\n return Response.json(result, { headers: { 'cache-control': 'no-store' } })\n } catch (error) {\n // Unavailable authoritative state is not permission to start a new task.\n return error instanceof Response ? error : failure(503, 'line_application_unavailable')\n }\n }\n}\n\nfunction failure(status: number, code: string): Response {\n return Response.json({ error: { code } }, { status, headers: { 'cache-control': 'no-store' } })\n}\n","import type { LineApplication, LineAttachment, SandboxInstance } from '@tangle-network/sandbox/core'\nimport type { OwnerApplicationSenderVerification } from './application-verification'\n\nexport interface ApplicationOwnerLines {\n /** Read with the same owner API key that started TEST and will attach. */\n getSenderVerification(lineId: string, testId: string): Promise<OwnerApplicationSenderVerification>\n}\n\n/** Attach a proved handset to the application's normal chat path. Platform\n * atomically consumes the one-use proof and checks this owner key again. */\nexport async function attachWorkspaceLine(input: {\n box: Pick<SandboxInstance, 'lines'>\n ownerLines: ApplicationOwnerLines\n lineId: string\n senderVerificationId: string\n application: LineApplication\n turnsPerDay?: number\n}): Promise<LineAttachment> {\n if (!/^lsv_[A-Za-z0-9_-]+$/.test(input.senderVerificationId)) {\n throw new TypeError('A valid sender verification id is required')\n }\n const verification = await input.ownerLines.getSenderVerification(input.lineId, input.senderVerificationId)\n const expiresAt = new Date(verification.expiresAt).getTime()\n if (verification.lineId !== input.lineId || verification.testId !== input.senderVerificationId\n || verification.state !== 'verified' || !verification.proof.signedInboundTestAt\n || !verification.proof.providerReplyAcknowledgedAt || !verification.proof.signedInboundConfirmAt\n || !Number.isFinite(expiresAt) || expiresAt <= Date.now()) {\n throw new TypeError('The selected line has no current verified sender proof')\n }\n const address = verification.approvedSender?.trim() ?? ''\n const turnsPerDay = input.turnsPerDay ?? 20\n if (!/^\\+[1-9]\\d{6,14}$/.test(address)) {\n throw new TypeError('The verified sender must be an E.164 phone number')\n }\n if (!Number.isSafeInteger(turnsPerDay) || turnsPerDay < 1 || turnsPerDay > 10_000) {\n throw new TypeError('A daily turn limit between 1 and 10000 is required')\n }\n const url = new URL(input.application.url)\n if (url.protocol !== 'https:' || url.username || url.password || url.hash) {\n throw new TypeError('The application callback must use HTTPS without URL credentials or a fragment')\n }\n if (!/^[\\x21-\\x7e]{1,1024}$/.test(input.application.binding)\n || !/^[\\x21-\\x7e]{16,512}$/.test(input.application.secret)) {\n throw new TypeError('A binding and a header-safe callback credential are required')\n }\n const attachment = {\n number: input.lineId,\n senderVerificationId: input.senderVerificationId,\n mode: 'personal',\n members: [{ address, role: 'owner' }],\n unknownSenders: 'reject',\n roles: { owner: { context: 'own', tools: 'act' } },\n respond: { kind: 'agent', application: { ...input.application } },\n limits: { turnsPerMemberPerDay: turnsPerDay },\n } satisfies Parameters<SandboxInstance['lines']['attach']>[0] & { senderVerificationId: string }\n return input.box.lines.attach(attachment)\n}\n","/** Public TEST data. The private CONFIRM reply is never returned to a browser. */\nexport interface ApplicationSenderVerificationStart {\n lineId: string\n testId: string\n state: 'awaiting_test'\n testText: string\n expiresAt: string\n}\n\n/** Browser-safe status from the owner server. No sender address is present. */\nexport interface ApplicationSenderVerification {\n lineId: string\n testId: string\n state: 'awaiting_test' | 'sending' | 'challenge_sent' | 'verified'\n | 'consumed' | 'cancelled' | 'superseded' | 'failed' | 'expired'\n expiresAt: string\n proof: {\n signedInboundTestAt: string | null\n providerReplyAcknowledgedAt: string | null\n signedInboundConfirmAt: string | null\n }\n}\n\n/** The owner-key SDK read includes the confirmed sender for the attach helper. */\nexport interface OwnerApplicationSenderVerification extends ApplicationSenderVerification {\n approvedSender?: string\n}\n\n/** Use at the host response boundary so approvedSender cannot enter page state. */\nexport function publicApplicationSenderVerification(\n result: OwnerApplicationSenderVerification,\n): ApplicationSenderVerification {\n return {\n lineId: result.lineId,\n testId: result.testId,\n state: result.state,\n expiresAt: result.expiresAt,\n proof: {\n signedInboundTestAt: result.proof.signedInboundTestAt,\n providerReplyAcknowledgedAt: result.proof.providerReplyAcknowledgedAt,\n signedInboundConfirmAt: result.proof.signedInboundConfirmAt,\n },\n }\n}\n"],"mappings":";;;;;;AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;;;ACEP,eAAsB,oBAAoB,OAOd;AAC1B,MAAI,CAAC,uBAAuB,KAAK,MAAM,oBAAoB,GAAG;AAC5D,UAAM,IAAI,UAAU,4CAA4C;AAAA,EAClE;AACA,QAAM,eAAe,MAAM,MAAM,WAAW,sBAAsB,MAAM,QAAQ,MAAM,oBAAoB;AAC1G,QAAM,YAAY,IAAI,KAAK,aAAa,SAAS,EAAE,QAAQ;AAC3D,MAAI,aAAa,WAAW,MAAM,UAAU,aAAa,WAAW,MAAM,wBACrE,aAAa,UAAU,cAAc,CAAC,aAAa,MAAM,uBACzD,CAAC,aAAa,MAAM,+BAA+B,CAAC,aAAa,MAAM,0BACvE,CAAC,OAAO,SAAS,SAAS,KAAK,aAAa,KAAK,IAAI,GAAG;AAC3D,UAAM,IAAI,UAAU,wDAAwD;AAAA,EAC9E;AACA,QAAM,UAAU,aAAa,gBAAgB,KAAK,KAAK;AACvD,QAAM,cAAc,MAAM,eAAe;AACzC,MAAI,CAAC,oBAAoB,KAAK,OAAO,GAAG;AACtC,UAAM,IAAI,UAAU,mDAAmD;AAAA,EACzE;AACA,MAAI,CAAC,OAAO,cAAc,WAAW,KAAK,c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,QAAU,SAAS;AAAA,QAAG,SAAS,MAAM;AAAA,QACxC,WAAW,MAAM;AAAA,QAAW,cAAc,MAAM;AAAA,MAClD,GAAG,KAAK;AACR,aAAO,SAAS,KAAK,QAAQ,EAAE,SAAS,EAAE,iBAAiB,WAAW,EAAE,CAAC;AAAA,IAC3E,SAAS,OAAO;AAEd,aAAO,iBAAiB,WAAW,QAAQ,QAAQ,KAAK,8BAA8B;AAAA,IACxF;AAAA,EACF;AACF;AAEA,SAAS,QAAQ,QAAgB,MAAwB;AACvD,SAAO,SAAS,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,QAAQ,SAAS,EAAE,iBAAiB,WAAW,EAAE,CAAC;AAChG;","names":[]}
|
|
@@ -1,15 +1,22 @@
|
|
|
1
|
+
import type { ApplicationSenderVerification, ApplicationSenderVerificationStart } from '../application-verification';
|
|
1
2
|
import type { LineConnectInput, LineSetupClient, LineSetupProps } from './contracts';
|
|
3
|
+
export type { ApplicationSenderVerification, ApplicationSenderVerificationStart } from '../application-verification';
|
|
2
4
|
export interface ApplicationLineConnectInput extends LineConnectInput {
|
|
3
|
-
|
|
5
|
+
senderVerificationId: string;
|
|
4
6
|
turnsPerDay: number;
|
|
5
7
|
}
|
|
6
8
|
export interface ApplicationLineSetupClient extends Omit<LineSetupClient, 'connect'> {
|
|
9
|
+
/** Host creates or finds the selected owned line, then starts TEST with its owner key. */
|
|
10
|
+
startSenderVerification(input: LineConnectInput): Promise<ApplicationSenderVerificationStart>;
|
|
11
|
+
/** Host returns only public fields. approvedSender never reaches the browser. */
|
|
12
|
+
getSenderVerification(lineId: string, testId: string): Promise<ApplicationSenderVerification>;
|
|
13
|
+
/** Host rechecks owner authority and consumes the proof during attach. */
|
|
7
14
|
connect(input: ApplicationLineConnectInput): Promise<void>;
|
|
8
15
|
}
|
|
9
|
-
export interface ApplicationLineSetupProps extends Omit<LineSetupProps, 'client' | 'canConnect'> {
|
|
16
|
+
export interface ApplicationLineSetupProps extends Omit<LineSetupProps, 'client' | 'canConnect' | 'connectPrerequisite'> {
|
|
10
17
|
client: ApplicationLineSetupClient;
|
|
11
18
|
/** Disable new grants without preventing disconnection of an existing line. */
|
|
12
19
|
enabled: boolean;
|
|
13
20
|
}
|
|
14
|
-
/**
|
|
21
|
+
/** Verify an owned handset before connecting its iMessage line to an application. */
|
|
15
22
|
export declare function ApplicationLineSetup(props: ApplicationLineSetupProps): import("react").JSX.Element;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { LineSetupProps } from './contracts';
|
|
2
2
|
/** Set up an owned identity through a host route backed by sandbox.lines and Hub. */
|
|
3
|
-
export declare function LineSetup({ client, scopeKey, initialTargetId, targetLabel, canManage, canConnect, showConnectionSetup, onNotice }: LineSetupProps): import("react").JSX.Element;
|
|
3
|
+
export declare function LineSetup({ client, scopeKey, initialTargetId, targetLabel, canManage, canConnect, showConnectionSetup, connectPrerequisite, setupDescription, emptyConnectionsMessage, onNotice }: LineSetupProps): import("react").JSX.Element;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Line, LineFromConnectionInput, LineMember, LineMemberPatch, LineMemberSpec } from '@tangle-network/sandbox';
|
|
2
|
+
import type { ReactNode } from 'react';
|
|
2
3
|
export type ConnectableLineTransport = LineFromConnectionInput['transport'];
|
|
3
4
|
export type LineBoxMode = 'per-member' | 'shared';
|
|
4
5
|
export type LineIdentityKind = 'handle' | 'number' | 'email';
|
|
@@ -78,6 +79,14 @@ export interface LineSetupProps {
|
|
|
78
79
|
/** Narrow new attachments without hiding disconnect controls; not server authorization. */
|
|
79
80
|
canConnect?: boolean;
|
|
80
81
|
showConnectionSetup?: boolean;
|
|
82
|
+
/** Product-specific step beside the selected line, before attach. The ready
|
|
83
|
+
* flag gates the button and is checked again when the user clicks it. */
|
|
84
|
+
connectPrerequisite?(input: LineConnectInput): {
|
|
85
|
+
content: ReactNode;
|
|
86
|
+
ready: boolean;
|
|
87
|
+
};
|
|
88
|
+
setupDescription?: string;
|
|
89
|
+
emptyConnectionsMessage?: string;
|
|
81
90
|
onNotice?(notice: {
|
|
82
91
|
kind: 'success' | 'error';
|
|
83
92
|
message: string;
|
|
@@ -3,4 +3,4 @@ export type { ConnectableLineTransport, LineAnswerTarget, LineBillingProps, Line
|
|
|
3
3
|
export { LineSetup } from './LineSetup';
|
|
4
4
|
export { LineMembers } from './LineMembers';
|
|
5
5
|
export { LineBilling } from './LineBilling';
|
|
6
|
-
export { ApplicationLineSetup, type ApplicationLineSetupProps, type ApplicationLineSetupClient, type ApplicationLineConnectInput } from './ApplicationLineSetup';
|
|
6
|
+
export { ApplicationLineSetup, type ApplicationLineSetupProps, type ApplicationLineSetupClient, type ApplicationLineConnectInput, type ApplicationSenderVerificationStart, type ApplicationSenderVerification } from './ApplicationLineSetup';
|
|
@@ -37,7 +37,7 @@ function matchesLineIdentity(line, identity, numberId) {
|
|
|
37
37
|
if (line.providerNumberId === null) return line.transport !== "whatsapp" && !identity.phoneNumberId && !identity.requiresPhoneNumberId;
|
|
38
38
|
return numberId === line.providerNumberId;
|
|
39
39
|
}
|
|
40
|
-
function LineSetup({ client, scopeKey, initialTargetId, targetLabel, canManage, canConnect = canManage, showConnectionSetup = true, onNotice }) {
|
|
40
|
+
function LineSetup({ client, scopeKey, initialTargetId, targetLabel, canManage, canConnect = canManage, showConnectionSetup = true, connectPrerequisite, setupDescription, emptyConnectionsMessage, onNotice }) {
|
|
41
41
|
const clientRef = useRef(client);
|
|
42
42
|
clientRef.current = client;
|
|
43
43
|
const sequence = useRef(0);
|
|
@@ -145,19 +145,22 @@ function LineSetup({ client, scopeKey, initialTargetId, targetLabel, canManage,
|
|
|
145
145
|
const reconnecting = Boolean(reconnectChoice && selected && occupiedLine && matchesLineIdentity(occupiedLine, selected.identity, enteredNumber));
|
|
146
146
|
const blockedByExistingLine = Boolean(occupied?.length && !reconnecting);
|
|
147
147
|
const answeringCount = snapshot?.lines.filter((line) => line.answering).length ?? 0;
|
|
148
|
+
const draft = selected && selectedTarget && selectedMode ? {
|
|
149
|
+
connectionId: selected.connection.id,
|
|
150
|
+
transport: selected.identity.transport,
|
|
151
|
+
...enteredNumber ? { phoneNumberId: enteredNumber } : {},
|
|
152
|
+
targetId: selectedTarget.id,
|
|
153
|
+
boxMode: selectedMode
|
|
154
|
+
} : null;
|
|
155
|
+
const prerequisite = draft ? connectPrerequisite?.(draft) : null;
|
|
156
|
+
const connectReady = Boolean(canManage && canConnect && draft && (prerequisite?.ready ?? true) && !(needsNumber && !enteredNumber) && !blockedByExistingLine && !busy && !loading && !refreshFailed);
|
|
148
157
|
async function connect() {
|
|
149
|
-
if (!
|
|
158
|
+
if (!connectReady || !draft || !selected) return;
|
|
150
159
|
const requestIncarnation = incarnation.current;
|
|
151
160
|
setBusy(true);
|
|
152
161
|
setError(null);
|
|
153
162
|
try {
|
|
154
|
-
await clientRef.current.connect(
|
|
155
|
-
connectionId: selected.connection.id,
|
|
156
|
-
transport: selected.identity.transport,
|
|
157
|
-
...enteredNumber ? { phoneNumberId: enteredNumber } : {},
|
|
158
|
-
targetId: selectedTarget.id,
|
|
159
|
-
boxMode: selectedMode
|
|
160
|
-
});
|
|
163
|
+
await clientRef.current.connect(draft);
|
|
161
164
|
if (!stillCurrent(requestIncarnation)) return;
|
|
162
165
|
const updated = await reload(requestIncarnation);
|
|
163
166
|
if (!stillCurrent(requestIncarnation)) return;
|
|
@@ -262,12 +265,13 @@ function LineSetup({ client, scopeKey, initialTargetId, targetLabel, canManage,
|
|
|
262
265
|
canManage && showConnectionSetup && (snapshot.connections === null || choices.length > 0 || allChoices.length === 0) && /* @__PURE__ */ jsxs("div", { className: "tangle-lines__setup", children: [
|
|
263
266
|
/* @__PURE__ */ jsx("span", { className: "tangle-lines__overline", children: "New line" }),
|
|
264
267
|
/* @__PURE__ */ jsx("h3", { children: "Connect an identity you own" }),
|
|
265
|
-
/* @__PURE__ */ jsx("p", { children: "Choose an identity already connected in Hub. Billing details appear below." }),
|
|
268
|
+
/* @__PURE__ */ jsx("p", { children: setupDescription ?? "Choose an identity already connected in Hub. Billing details appear below." }),
|
|
266
269
|
snapshot.connections === null ? /* @__PURE__ */ jsxs("div", { className: "tangle-lines__error", role: "status", children: [
|
|
267
270
|
/* @__PURE__ */ jsx("span", { children: "Hub connections could not be read. Check Hub access and try again." }),
|
|
268
271
|
/* @__PURE__ */ jsx("button", { type: "button", disabled: loading, onClick: retry, children: "Retry" })
|
|
269
272
|
] }) : availableKinds.length === 0 ? /* @__PURE__ */ jsxs("p", { className: "tangle-lines__empty", children: [
|
|
270
|
-
"Connect an owned handle, number, or mailbox in Hub, then
|
|
273
|
+
emptyConnectionsMessage ?? "Connect an owned handle, number, or mailbox in Hub, then",
|
|
274
|
+
" ",
|
|
271
275
|
/* @__PURE__ */ jsx("button", { type: "button", disabled: loading, onClick: retry, children: "reload" }),
|
|
272
276
|
"."
|
|
273
277
|
] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
@@ -312,7 +316,8 @@ function LineSetup({ client, scopeKey, initialTargetId, targetLabel, canManage,
|
|
|
312
316
|
] })
|
|
313
317
|
] }),
|
|
314
318
|
reconnectChoice && blockedByExistingLine && /* @__PURE__ */ jsx("p", { className: "tangle-lines__warning", children: "Enter this line's current provider number ID to reconnect." }),
|
|
315
|
-
|
|
319
|
+
prerequisite?.content,
|
|
320
|
+
/* @__PURE__ */ jsx("button", { className: "tangle-lines__primary", type: "button", disabled: !connectReady, onClick: () => void connect(), children: busy ? reconnectChoice ? "Reconnecting\u2026" : "Connecting\u2026" : `${reconnectChoice ? "Reconnect" : "Connect"} ${selected ? TRANSPORT[selected.identity.transport] : "line"}` })
|
|
316
321
|
] })
|
|
317
322
|
] })
|
|
318
323
|
] })
|
|
@@ -575,92 +580,217 @@ function LineBilling({ view }) {
|
|
|
575
580
|
}
|
|
576
581
|
|
|
577
582
|
// src/hosted-agent/react/ApplicationLineSetup.tsx
|
|
578
|
-
import { useMemo, useState as useState3 } from "react";
|
|
583
|
+
import { useEffect as useEffect3, useMemo, useState as useState3 } from "react";
|
|
579
584
|
import { Fragment as Fragment4, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
|
|
585
|
+
function verificationError(cause) {
|
|
586
|
+
return cause instanceof Error ? cause.message : "The phone test could not be checked. Try again.";
|
|
587
|
+
}
|
|
588
|
+
function draftKey(input) {
|
|
589
|
+
return JSON.stringify(input);
|
|
590
|
+
}
|
|
591
|
+
function expiry(value) {
|
|
592
|
+
const time = new Date(value).getTime();
|
|
593
|
+
return Number.isFinite(time) ? time : 0;
|
|
594
|
+
}
|
|
580
595
|
function ApplicationLineSetup(props) {
|
|
581
596
|
return /* @__PURE__ */ jsx4(ApplicationLineSetupScope, { ...props }, props.scopeKey);
|
|
582
597
|
}
|
|
583
598
|
function ApplicationLineSetupScope({ client, enabled, ...props }) {
|
|
584
|
-
const [operatorAddress, setAddress] = useState3("");
|
|
585
599
|
const [limit, setLimit] = useState3("20");
|
|
586
|
-
const [
|
|
587
|
-
const
|
|
600
|
+
const [session, setSession] = useState3(null);
|
|
601
|
+
const [pending, setPending] = useState3(null);
|
|
602
|
+
const [error, setError] = useState3(null);
|
|
603
|
+
const [needsStatusRefresh, setNeedsStatusRefresh] = useState3(false);
|
|
604
|
+
const [now, setNow] = useState3(() => Date.now());
|
|
588
605
|
const turnsPerDay = Number(limit);
|
|
589
|
-
const
|
|
590
|
-
|
|
591
|
-
|
|
606
|
+
const validLimit = Number.isSafeInteger(turnsPerDay) && turnsPerDay >= 1 && turnsPerDay <= 1e4;
|
|
607
|
+
useEffect3(() => {
|
|
608
|
+
const timer = setInterval(() => setNow(Date.now()), 1e3);
|
|
609
|
+
return () => clearInterval(timer);
|
|
610
|
+
}, []);
|
|
611
|
+
function activeFor(input) {
|
|
612
|
+
return session?.draftKey === draftKey(input) ? session : null;
|
|
613
|
+
}
|
|
614
|
+
function verifiedFor(input, time) {
|
|
615
|
+
const active = activeFor(input);
|
|
616
|
+
return Boolean(active && !needsStatusRefresh && !pending && active.status.state === "verified" && active.status.proof.signedInboundTestAt && active.status.proof.providerReplyAcknowledgedAt && active.status.proof.signedInboundConfirmAt && expiry(active.status.expiresAt) > time);
|
|
617
|
+
}
|
|
618
|
+
async function start(input) {
|
|
619
|
+
const key = draftKey(input);
|
|
620
|
+
if (!enabled || !props.canManage || !validLimit || pending || input.transport !== "imessage") return;
|
|
621
|
+
setPending({ kind: "start", draftKey: key });
|
|
622
|
+
setError(null);
|
|
623
|
+
setNeedsStatusRefresh(true);
|
|
624
|
+
try {
|
|
625
|
+
const result = await client.startSenderVerification(input);
|
|
626
|
+
if (!result.lineId || !result.testId || !result.testText || result.state !== "awaiting_test" || expiry(result.expiresAt) <= Date.now()) throw new Error("The phone test could not be started. Try again.");
|
|
627
|
+
setSession({
|
|
628
|
+
draftKey: key,
|
|
629
|
+
start: result,
|
|
630
|
+
status: {
|
|
631
|
+
lineId: result.lineId,
|
|
632
|
+
testId: result.testId,
|
|
633
|
+
state: result.state,
|
|
634
|
+
expiresAt: result.expiresAt,
|
|
635
|
+
proof: { signedInboundTestAt: null, providerReplyAcknowledgedAt: null, signedInboundConfirmAt: null }
|
|
636
|
+
}
|
|
637
|
+
});
|
|
638
|
+
setNow(Date.now());
|
|
639
|
+
} catch (cause) {
|
|
640
|
+
setError(verificationError(cause));
|
|
641
|
+
} finally {
|
|
642
|
+
setPending(null);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
async function check(active) {
|
|
646
|
+
if (pending) return;
|
|
647
|
+
setPending({ kind: "check", draftKey: active.draftKey });
|
|
648
|
+
setError(null);
|
|
649
|
+
setNeedsStatusRefresh(true);
|
|
650
|
+
try {
|
|
651
|
+
const result = await client.getSenderVerification(active.start.lineId, active.start.testId);
|
|
652
|
+
if (result.lineId !== active.start.lineId || result.testId !== active.start.testId)
|
|
653
|
+
throw new Error("The phone test changed. Start a new test.");
|
|
654
|
+
const status = {
|
|
655
|
+
lineId: result.lineId,
|
|
656
|
+
testId: result.testId,
|
|
657
|
+
state: result.state,
|
|
658
|
+
expiresAt: result.expiresAt,
|
|
659
|
+
proof: {
|
|
660
|
+
signedInboundTestAt: result.proof.signedInboundTestAt,
|
|
661
|
+
providerReplyAcknowledgedAt: result.proof.providerReplyAcknowledgedAt,
|
|
662
|
+
signedInboundConfirmAt: result.proof.signedInboundConfirmAt
|
|
663
|
+
}
|
|
664
|
+
};
|
|
665
|
+
setSession((current) => current?.start.testId === active.start.testId ? { ...current, status } : current);
|
|
666
|
+
setNeedsStatusRefresh(false);
|
|
667
|
+
setNow(Date.now());
|
|
668
|
+
} catch (cause) {
|
|
669
|
+
setError(verificationError(cause));
|
|
670
|
+
} finally {
|
|
671
|
+
setPending(null);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
592
674
|
const lineClient = useMemo(() => ({
|
|
593
|
-
load
|
|
675
|
+
async load() {
|
|
676
|
+
const snapshot = await client.load();
|
|
677
|
+
return {
|
|
678
|
+
...snapshot,
|
|
679
|
+
connections: snapshot.connections?.map((connection) => ({
|
|
680
|
+
...connection,
|
|
681
|
+
identities: connection.providerId === "inkbox" ? connection.identities.filter((identity) => identity.transport === "imessage") : []
|
|
682
|
+
})).filter((connection) => connection.identities.length > 0) ?? null
|
|
683
|
+
};
|
|
684
|
+
},
|
|
594
685
|
disconnect: (id, expectedAttachmentId) => client.disconnect(id, expectedAttachmentId),
|
|
595
|
-
connect
|
|
596
|
-
|
|
597
|
-
|
|
686
|
+
async connect(input) {
|
|
687
|
+
const active = activeFor(input);
|
|
688
|
+
if (!enabled || !props.canManage || !validLimit || !verifiedFor(input, Date.now()) || !active)
|
|
689
|
+
throw new Error("Verify the selected phone before connecting this line");
|
|
690
|
+
try {
|
|
691
|
+
await client.connect({ ...input, senderVerificationId: active.start.testId, turnsPerDay });
|
|
692
|
+
setSession(null);
|
|
693
|
+
} catch (cause) {
|
|
694
|
+
setNeedsStatusRefresh(true);
|
|
695
|
+
throw cause;
|
|
696
|
+
}
|
|
598
697
|
}
|
|
599
|
-
}), [client,
|
|
698
|
+
}), [client, enabled, props.canManage, session, turnsPerDay, validLimit, needsStatusRefresh, pending]);
|
|
699
|
+
function prerequisite(input) {
|
|
700
|
+
const key = draftKey(input);
|
|
701
|
+
const active = activeFor(input);
|
|
702
|
+
const expired = Boolean(active && expiry(active.status.expiresAt) <= now);
|
|
703
|
+
const verified = verifiedFor(input, now);
|
|
704
|
+
const inProgress = active && !expired && ["awaiting_test", "sending", "challenge_sent"].includes(active.status.state);
|
|
705
|
+
const busy = pending?.draftKey === key;
|
|
706
|
+
const canStart = enabled && props.canManage && validLimit && !pending && input.transport === "imessage";
|
|
707
|
+
const canCheck = Boolean((inProgress || active?.status.state === "verified") && !pending);
|
|
708
|
+
return {
|
|
709
|
+
ready: validLimit && verified,
|
|
710
|
+
content: /* @__PURE__ */ jsxs4("div", { className: "tangle-lines__verification", "aria-label": "Phone verification", children: [
|
|
711
|
+
/* @__PURE__ */ jsx4("h4", { children: "Verify your phone" }),
|
|
712
|
+
/* @__PURE__ */ jsx4("p", { children: "Use the phone that will send commands to this line. Connection opens after that phone is verified." }),
|
|
713
|
+
!validLimit && /* @__PURE__ */ jsx4("p", { className: "tangle-lines__warning", children: "Enter a daily message limit from 1 to 10,000 first." }),
|
|
714
|
+
!active || expired || ["consumed", "cancelled", "superseded", "failed", "expired"].includes(active.status.state) ? /* @__PURE__ */ jsxs4(Fragment4, { children: [
|
|
715
|
+
active && /* @__PURE__ */ jsx4("p", { role: "status", children: "This phone test can no longer connect the line. Start a new test." }),
|
|
716
|
+
/* @__PURE__ */ jsx4(
|
|
717
|
+
"button",
|
|
718
|
+
{
|
|
719
|
+
type: "button",
|
|
720
|
+
className: "tangle-lines__secondary",
|
|
721
|
+
disabled: !canStart,
|
|
722
|
+
onClick: () => void start(input),
|
|
723
|
+
children: busy && pending?.kind === "start" ? "Starting test\u2026" : "Start phone test"
|
|
724
|
+
}
|
|
725
|
+
)
|
|
726
|
+
] }) : /* @__PURE__ */ jsxs4(Fragment4, { children: [
|
|
727
|
+
/* @__PURE__ */ jsx4("p", { children: "Text this exact message to the selected line from your phone:" }),
|
|
728
|
+
/* @__PURE__ */ jsx4("code", { className: "tangle-lines__test-text", children: active.start.testText }),
|
|
729
|
+
/* @__PURE__ */ jsx4("p", { children: "Follow the private reply on your phone. No confirmation code is entered here." }),
|
|
730
|
+
/* @__PURE__ */ jsxs4("p", { className: "tangle-lines__verification-expiry", children: [
|
|
731
|
+
"Test expires at ",
|
|
732
|
+
new Date(active.status.expiresAt).toLocaleTimeString(),
|
|
733
|
+
"."
|
|
734
|
+
] }),
|
|
735
|
+
verified && /* @__PURE__ */ jsx4("p", { className: "tangle-lines__verified", role: "status", children: "Phone verified. You can connect this line." }),
|
|
736
|
+
/* @__PURE__ */ jsxs4("div", { className: "tangle-lines__verification-actions", children: [
|
|
737
|
+
!verified && /* @__PURE__ */ jsx4("span", { role: "status", children: active.status.state === "verified" ? "Check verification again before connecting." : active.status.state === "challenge_sent" ? "Confirmation sent. Reply from the same phone, then check again." : active.status.state === "sending" ? "Sending confirmation\u2026" : "Waiting for your test message." }),
|
|
738
|
+
/* @__PURE__ */ jsx4(
|
|
739
|
+
"button",
|
|
740
|
+
{
|
|
741
|
+
type: "button",
|
|
742
|
+
className: "tangle-lines__secondary",
|
|
743
|
+
disabled: !canCheck,
|
|
744
|
+
onClick: () => void check(active),
|
|
745
|
+
children: busy && pending?.kind === "check" ? "Checking\u2026" : "Check verification"
|
|
746
|
+
}
|
|
747
|
+
)
|
|
748
|
+
] })
|
|
749
|
+
] }),
|
|
750
|
+
error && /* @__PURE__ */ jsx4("p", { className: "tangle-lines__verification-error", role: "alert", children: error })
|
|
751
|
+
] })
|
|
752
|
+
};
|
|
753
|
+
}
|
|
600
754
|
return /* @__PURE__ */ jsxs4(Fragment4, { children: [
|
|
601
755
|
props.canManage && /* @__PURE__ */ jsxs4("section", { className: "tangle-lines tangle-lines--application", "aria-label": "Application access", children: [
|
|
602
756
|
/* @__PURE__ */ jsxs4("header", { className: "tangle-lines__application-heading", children: [
|
|
603
757
|
/* @__PURE__ */ jsx4("h2", { children: "Text your workspace" }),
|
|
604
|
-
/* @__PURE__ */ jsx4("p", { children: "
|
|
758
|
+
/* @__PURE__ */ jsx4("p", { children: "Connect an owned Inkbox iMessage line to a conversation. Verify your phone before it can use application access and compute." })
|
|
605
759
|
] }),
|
|
606
760
|
!enabled ? /* @__PURE__ */ jsxs4("div", { className: "tangle-lines__notice", role: "status", children: [
|
|
607
761
|
/* @__PURE__ */ jsx4("strong", { children: "New connections are disabled" }),
|
|
608
762
|
/* @__PURE__ */ jsx4("p", { children: "You can still review and disconnect an existing line below." })
|
|
609
763
|
] }) : /* @__PURE__ */ jsxs4("div", { className: "tangle-lines__authorization", children: [
|
|
610
|
-
/* @__PURE__ */ jsxs4("
|
|
611
|
-
|
|
612
|
-
/* @__PURE__ */ jsx4("p", { children: "Only this sender can issue commands through the line you connect." })
|
|
613
|
-
] }),
|
|
614
|
-
/* @__PURE__ */ jsxs4("div", { className: "tangle-lines__fields", children: [
|
|
615
|
-
/* @__PURE__ */ jsxs4("label", { children: [
|
|
616
|
-
"Authorized sender",
|
|
617
|
-
/* @__PURE__ */ jsx4(
|
|
618
|
-
"input",
|
|
619
|
-
{
|
|
620
|
-
value: operatorAddress,
|
|
621
|
-
onChange: (e) => {
|
|
622
|
-
setAddress(e.target.value);
|
|
623
|
-
setApproved(null);
|
|
624
|
-
},
|
|
625
|
-
autoComplete: "off",
|
|
626
|
-
placeholder: "+15550100001 or your Apple ID / email"
|
|
627
|
-
}
|
|
628
|
-
)
|
|
629
|
-
] }),
|
|
630
|
-
/* @__PURE__ */ jsxs4("label", { children: [
|
|
631
|
-
"Maximum messages per day",
|
|
632
|
-
/* @__PURE__ */ jsx4(
|
|
633
|
-
"input",
|
|
634
|
-
{
|
|
635
|
-
type: "number",
|
|
636
|
-
min: 1,
|
|
637
|
-
max: 1e4,
|
|
638
|
-
step: 1,
|
|
639
|
-
value: limit,
|
|
640
|
-
onChange: (e) => {
|
|
641
|
-
setLimit(e.target.value);
|
|
642
|
-
setApproved(null);
|
|
643
|
-
}
|
|
644
|
-
}
|
|
645
|
-
)
|
|
646
|
-
] })
|
|
647
|
-
] }),
|
|
648
|
-
/* @__PURE__ */ jsxs4("label", { className: "tangle-lines__delegation", children: [
|
|
764
|
+
/* @__PURE__ */ jsxs4("label", { className: "tangle-lines__limit", children: [
|
|
765
|
+
"Maximum messages per day",
|
|
649
766
|
/* @__PURE__ */ jsx4(
|
|
650
767
|
"input",
|
|
651
768
|
{
|
|
652
|
-
type: "
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
769
|
+
type: "number",
|
|
770
|
+
min: 1,
|
|
771
|
+
max: 1e4,
|
|
772
|
+
step: 1,
|
|
773
|
+
value: limit,
|
|
774
|
+
onChange: (event) => setLimit(event.target.value)
|
|
656
775
|
}
|
|
657
|
-
)
|
|
658
|
-
"I authorize this sender to work in the conversation I select below using my application access and compute budget."
|
|
776
|
+
)
|
|
659
777
|
] }),
|
|
660
|
-
/* @__PURE__ */ jsx4("p", { className: "tangle-lines__fine-print", children: "The
|
|
778
|
+
/* @__PURE__ */ jsx4("p", { className: "tangle-lines__fine-print", children: "The message limit is not a dollar cap. STOP stops replies, not an already accepted task; cancel that task in the application." })
|
|
661
779
|
] })
|
|
662
780
|
] }),
|
|
663
|
-
/* @__PURE__ */ jsx4(
|
|
781
|
+
/* @__PURE__ */ jsx4(
|
|
782
|
+
LineSetup,
|
|
783
|
+
{
|
|
784
|
+
...props,
|
|
785
|
+
targetLabel: props.targetLabel ?? "Conversation",
|
|
786
|
+
client: lineClient,
|
|
787
|
+
canConnect: props.canManage && enabled,
|
|
788
|
+
showConnectionSetup: enabled,
|
|
789
|
+
connectPrerequisite: prerequisite,
|
|
790
|
+
setupDescription: "Choose an owned Inkbox iMessage line and the conversation it will answer.",
|
|
791
|
+
emptyConnectionsMessage: "Add an owned Inkbox iMessage handle in Hub, then"
|
|
792
|
+
}
|
|
793
|
+
)
|
|
664
794
|
] });
|
|
665
795
|
}
|
|
666
796
|
export {
|