instar 1.3.624 → 1.3.625

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.
@@ -19699,6 +19699,159 @@ export function createRoutes(ctx) {
19699
19699
  res.status(502).json({ error: 'could not reach the machine doing the login — try again, or re-tap Approve' });
19700
19700
  }
19701
19701
  });
19702
+ // account-machine-matrix (Account × Machine matrix) — PIN-GATED orchestrator over the
19703
+ // already-shipped PIN→mandate→enroll-start chain. The Subscriptions-tab matrix "Set up"
19704
+ // tap calls this with {accountId, machineId, pin}: it requires the dashboard PIN (the only
19705
+ // proof of operator presence — the AGENT also holds the Bearer, FD4), resolves the account
19706
+ // email + agents pair SERVER-SIDE from pool state (never from the body, FD3/FD8), issues the
19707
+ // per-(account, targetMachine) account-follow-me mandate exactly as /mandate/issue-for-machine
19708
+ // does, then drives the EXISTING mandate-gated enroll/start (self → loopback; peer → deliver
19709
+ // the signed mandate + remote enroll/start, the proven adriana cross-machine path). It adds NO
19710
+ // new authority — it just drives the existing chain in one call so the frontend never handles
19711
+ // fingerprints or raw mandate JSON. Idempotent: a re-tap reuses an existing valid pending login
19712
+ // for this pair (no duplicate, no stacked mandate). Dark behind multiMachine.accountFollowMe.
19713
+ router.post('/subscription-pool/matrix/start-cell', async (req, res) => {
19714
+ const afmCfg = ctx.config.multiMachine?.accountFollowMe;
19715
+ if (!resolveDevAgentGate(afmCfg?.enabled, ctx.config)) {
19716
+ res.status(503).json({ error: 'account follow-me not enabled' });
19717
+ return;
19718
+ }
19719
+ if (!ctx.coordination) {
19720
+ res.status(503).json({ error: 'coordination mandate engine unavailable (no stateDir or init failed)' });
19721
+ return;
19722
+ }
19723
+ if (!ctx.enrollmentWizard || !ctx.subscriptionPool) {
19724
+ res.status(503).json({ error: 'enrollment wizard or subscription pool not configured' });
19725
+ return;
19726
+ }
19727
+ const b = req.body ?? {};
19728
+ if (typeof b.accountId !== 'string' || !b.accountId.trim() || typeof b.machineId !== 'string' || !b.machineId.trim()) {
19729
+ res.status(400).json({ error: 'accountId and machineId are required' });
19730
+ return;
19731
+ }
19732
+ // THE LOAD-BEARING GATE (FD4): the dashboard PIN proves operator presence. checkMandatePin
19733
+ // is the EXACT mechanism /mandate/issue-for-machine uses; a missing/invalid PIN sends its own
19734
+ // 401/403/429 response — never start an enrollment without it. The agent shares the Bearer, so
19735
+ // Bearer-only would let any agent session start a cross-machine account login with no operator.
19736
+ if (!checkMandatePin(req, res))
19737
+ return;
19738
+ const accountId = b.accountId.trim();
19739
+ const machineId = b.machineId.trim();
19740
+ const selfMachineId = ctx.meshSelfId ?? ctx.config.machineId ?? 'local';
19741
+ const isSelf = machineId === selfMachineId;
19742
+ const localFp = resolveAgentFingerprint(ctx);
19743
+ // SELF-only idempotency (spec): a re-tap on a cell already mid-setup must REUSE the existing
19744
+ // pending login (correct expectedEmail + un-expired) rather than minting a new mandate / a
19745
+ // duplicate login. Peer-target idempotency is left to the peer's own enroll/start (we never
19746
+ // read a peer's pending() from here). The configHome is per-account so the pane identity is 1:1.
19747
+ if (isSelf) {
19748
+ try {
19749
+ const { resolveFollowMeEnrollTarget } = await import('../core/resolveFollowMeEnrollTarget.js');
19750
+ const localAccounts = ctx.subscriptionPool.list().map((a) => ({
19751
+ id: a.id, email: a.email, nickname: a.nickname, provider: a.provider, framework: a.framework,
19752
+ }));
19753
+ const peerViews = ctx.accountFollowMePeerViews ? await ctx.accountFollowMePeerViews() : [];
19754
+ const target = resolveFollowMeEnrollTarget({ accountId, localAccounts, peerViews });
19755
+ if (!target.resolved) {
19756
+ console.log(`[matrix] start-cell accountId=${accountId} machineId=${machineId} outcome=cannot-resolve-email`);
19757
+ res.status(409).json({ error: 'cannot resolve approved account email' });
19758
+ return;
19759
+ }
19760
+ const existing = ctx.enrollmentWizard.pending().find((l) => l.id === accountId && l.status === 'pending'
19761
+ && Date.parse(l.ttlExpiresAt) > Date.now()
19762
+ && (!l.expectedEmail || l.expectedEmail === target.expectedEmail));
19763
+ if (existing) {
19764
+ console.log(`[matrix] start-cell accountId=${accountId} machineId=${machineId} outcome=reused-pending`);
19765
+ res.status(201).json({ verificationUrl: existing.verificationUrl, loginId: existing.id, machineId, reused: true });
19766
+ return;
19767
+ }
19768
+ }
19769
+ catch (err) {
19770
+ res.status(500).json({ error: err instanceof Error ? err.message : 'matrix start-cell pre-check failed' });
19771
+ return;
19772
+ }
19773
+ }
19774
+ // Issue the per-(account, targetMachine) account-follow-me mandate — EXACTLY the bounds
19775
+ // /mandate/issue-for-machine writes (R1 exact-bounds, re-mint), PIN already verified above.
19776
+ // The agents pair is this Echo identity's routing fingerprint (issuer === target identity:
19777
+ // the agent following its own account onto another machine), as the scan card does.
19778
+ const expiresAt = new Date(Date.now() + 60 * 60 * 1000).toISOString();
19779
+ let mandateId;
19780
+ try {
19781
+ const mandate = ctx.coordination.store.issue({
19782
+ scope: 'account-follow-me',
19783
+ agents: [localFp, localFp],
19784
+ authorities: [
19785
+ { action: 'account-follow-me', bounds: { accountId, targetMachineId: machineId, mechanism: 're-mint' } },
19786
+ ],
19787
+ author: 'justin',
19788
+ expiresAt,
19789
+ });
19790
+ mandateId = mandate.id;
19791
+ // For a PEER target, deliver the signed mandate over the mesh first (the proven R4a path
19792
+ // that enrolled adriana); the peer's enroll/start re-verifies the issuance signature.
19793
+ if (!isSelf) {
19794
+ if (!ctx.packageMandateForDelivery || !ctx.deliverMandateToMachine) {
19795
+ res.status(503).json({ error: 'cross-machine mandate delivery unavailable (no mesh identity)' });
19796
+ return;
19797
+ }
19798
+ const portable = ctx.packageMandateForDelivery(mandate);
19799
+ const outcome = await ctx.deliverMandateToMachine({ targetMachineId: machineId, portable });
19800
+ if (!outcome.ok) {
19801
+ console.log(`[matrix] start-cell accountId=${accountId} machineId=${machineId} outcome=deliver-failed`);
19802
+ res.status(502).json({ error: 'could not deliver authorization to the target machine — try again in a moment', retryable: true });
19803
+ return;
19804
+ }
19805
+ }
19806
+ }
19807
+ catch (err) {
19808
+ res.status(500).json({ error: err instanceof Error ? err.message : 'matrix mandate issuance failed' });
19809
+ return;
19810
+ }
19811
+ // Drive the EXISTING mandate-gated enroll/start (no reimplementation of email resolution /
19812
+ // S7 / configHome / driveLogin). self → loopback; peer → the peer's local enroll/start. On
19813
+ // success it returns { login }; on an unresolvable email a 409; on a drive failure a 502.
19814
+ let baseUrl;
19815
+ if (isSelf) {
19816
+ baseUrl = `http://${ctx.config.host || '127.0.0.1'}:${ctx.config.port}`;
19817
+ }
19818
+ else {
19819
+ const peer = (ctx.resolvePeerUrls?.() ?? []).find((p) => p.machineId === machineId);
19820
+ if (!peer) {
19821
+ console.log(`[matrix] start-cell accountId=${accountId} machineId=${machineId} outcome=peer-unreachable`);
19822
+ res.status(502).json({ error: `target machine ${machineId} is not reachable right now — try again in a moment`, retryable: true });
19823
+ return;
19824
+ }
19825
+ baseUrl = peer.url;
19826
+ }
19827
+ try {
19828
+ const r = await fetch(`${baseUrl}/subscription-pool/follow-me/enroll/start`, {
19829
+ method: 'POST',
19830
+ headers: { Authorization: `Bearer ${ctx.config.authToken}`, 'Content-Type': 'application/json' },
19831
+ body: JSON.stringify({ mandateId, accountId }),
19832
+ signal: AbortSignal.timeout(40_000),
19833
+ });
19834
+ const body = await r.json().catch(() => ({}));
19835
+ if (r.status === 201 && body.login?.verificationUrl) {
19836
+ console.log(`[matrix] start-cell accountId=${accountId} machineId=${machineId} outcome=started`);
19837
+ res.status(201).json({ verificationUrl: body.login.verificationUrl, loginId: body.login.id ?? accountId, machineId });
19838
+ return;
19839
+ }
19840
+ if (r.status === 409) {
19841
+ console.log(`[matrix] start-cell accountId=${accountId} machineId=${machineId} outcome=cannot-resolve-email`);
19842
+ res.status(409).json({ error: body.error || 'cannot resolve approved account email' });
19843
+ return;
19844
+ }
19845
+ // Mandate issued but enroll-start failed (drive throw / unreachable / other). Honest
19846
+ // retryable 502 — the unused mandate lapses by its TTL; a re-tap reuses or re-mints.
19847
+ console.log(`[matrix] start-cell accountId=${accountId} machineId=${machineId} outcome=enroll-start-failed`);
19848
+ res.status(502).json({ error: body.error || 'could not start the sign-in on the target — try again', retryable: true });
19849
+ }
19850
+ catch (err) {
19851
+ console.log(`[matrix] start-cell accountId=${accountId} machineId=${machineId} outcome=enroll-start-error`);
19852
+ res.status(502).json({ error: 'could not reach the machine doing the login — try again', retryable: true });
19853
+ }
19854
+ });
19702
19855
  // Single-segment path → no collision with /enroll/:id/complete (3 segments).
19703
19856
  router.post('/subscription-pool/enroll/reissue-expired', async (_req, res) => {
19704
19857
  if (!ctx.enrollmentWizard) {