5mghost-yonder 0.4.0__py3-none-any.whl

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.
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.4
2
+ Name: 5mghost-yonder
3
+ Version: 0.4.0
4
+ Summary: Standalone Yonder CLI and bundled agent skill
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+
8
+ # M2 薄 CLI 离线模块
9
+
10
+ 2026-11-08:新增独立 `local-execute` / `local-read --local-config <私有配置>` 分支,供 Reddit/YouTube 已实现的匿名本地能力调用,默认逐 action 关闭;不加载下文远程身份 fixture。配置、实际调用与收据边界见 [`../local-coordinator/LOCAL-LAUNCHER.md`](../local-coordinator/LOCAL-LAUNCHER.md),Skill见 [`../shared-skill-m2/local/SKILL.md`](../shared-skill-m2/local/SKILL.md)。下文仍描述原离线CLI,不扩大原fixture资格。
11
+
12
+ 本模块只运行显式 fixture。能力清单决定 action 的远程/本地位置;只有装配了合成适配器的 action 可执行。未知 action、未知位置和缺适配器均拒绝,不自动切换来源。
13
+
14
+ `cli.py` 提供 execute、recover、cancel、event、save。命令行以 stdin 接收有界 JSON;必须显式传 `--fixture`,正文包含 `fixture` 与 `input`。测试中的 `test_cli_executable_explicit_fixture_and_no_ambient_key` 展示可运行装配。默认不读取环境 Key、真实个人配置或任何钥匙串,未显式装配返回 `ADAPTER_BLOCKED`。这是离线入口,不是可公开发行的 provider CLI。
15
+
16
+ - `auth_loader.py` 复用 1.12 SDK;受信 callback 逐次验证身份,凭据不进入 CLI 输出或回执。
17
+ - `adapters.py` 的 M1 请求/响应只经过注入函数,`m1-fixture.mjs` 消费既有 M1 schema。没有 HTTP socket 或 provider 调用。
18
+ - `receipt.py` 在自建私有临时根记录发送意图、进度摘要、正文 blob 引用及保存事实;unknown 只查询已知 operation,不重发 create。
19
+ - `result-store.mjs` 调用既有 ResultStore 的显式 M2 保存入口。不可变 data→log→manifest→reference→readback 后才报 saved;新进度需要新 commit,旧数据不覆盖。
20
+
21
+ 临时根从 TMPDIR/tempfile 运行时解析。保存根永久绑定一个回执根;另一回执根拒绝接管。原 SafeDirectory 仅支持 Linux `/proc`,Mac 返回 `SAVE_UNSUPPORTED`。本轮注入 saver 的通过不证明物理持久性;Linux 集成入口尚须 Eve 外跑。
22
+
23
+ ```sh
24
+ PYTHONDONTWRITEBYTECODE=1 ~/.local/bin/python3 -B -m unittest discover -s packages/yonder-cli/tests
25
+ node --test packages/yonder-cli/tests/integration.mjs
26
+ ```
27
+
28
+ 第二条仅在 Linux 隔离临时根执行,属于 heavy integration;不要在 Mac 将失败当作 skip 通过。运行前提供现有审核的 PyYAML 6.0.2、Node 24.21.0 及锁版 M1 依赖,不安装新包。本机无 uv,Python 使用 `~/.local/bin/python3` 替代 `uv run`。正式状态、生产、真实来源/客户端/OS 与发行资格均不因本模块提升。
@@ -0,0 +1,25 @@
1
+ yonder_cli/__init__.py,sha256=uNLQNQjQ7WZvM2M5Lpa7VufiYauB_yOjVV6HaWrcM7Y,60
2
+ yonder_cli/adapters.py,sha256=JKyPjSbIt4tqePpM2AFajxbxlGRraAqVN-18nIYKPyw,6819
3
+ yonder_cli/auth_loader.py,sha256=50fuX5LVZvQOwuuqKNlCcYhe1aDuQVpHIkYva1bePBA,534
4
+ yonder_cli/beta_auth.py,sha256=Wo3NTiS99TRjIbby11cFT8zolbOvauxMV86feocOZD0,41788
5
+ yonder_cli/cli.py,sha256=i3TzvkkTsmBbfcvayWM7Id1a-eYRYyawfYIHKQXDYJk,16254
6
+ yonder_cli/fixture.py,sha256=Y3K5ikPzI-j9U2WlQX-SLUAFoem_iiARAWnYE_OXWUE,4144
7
+ yonder_cli/m1-fixture.mjs,sha256=VDTz4sPKZFQKeTBCq8RNWt6gT_KXsFwsRCWiU1UXFE4,728
8
+ yonder_cli/query_client.py,sha256=2DLH6VyUOD9iQy82FqTklyBQDCJnfvA52Bw7boM54as,39235
9
+ yonder_cli/receipt.py,sha256=AshwwCoHJw5pwc75NRHsBrtd33fe-H85o8O55Qw-xwU,7150
10
+ yonder_cli/result-store.mjs,sha256=_WPoAO68oPe5q0BZolkTYoAENDlvlaeAvNv9Qf0Xa4g,918
11
+ yonder_cli/_vendor/client_auth/sdk.py,sha256=6yhtiwfhtCcGwCc4wrfQkXaY6hRxSAV1NrzBhOcJ9tM,21142
12
+ yonder_cli/_vendor/client_auth/storage.py,sha256=MbuXfhn2RIt3N7zmuoXNtdQxb7qd46xYBQbEjmmcNjU,21574
13
+ yonder_cli/_vendor/client_auth/tests.py,sha256=FSfHRx1XZn-jlVirwxzvAmDvSHaVdjl5Glk9QN99RZA,56252
14
+ yonder_cli/_vendor/client_auth/transport.py,sha256=nuQZKTR-nZh7cmWqFTsq7lpjI0hTttHDfDbqTjUeyF4,4825
15
+ yonder_cli_skill/SKILL.md,sha256=r_wktlokisNUGCSEdpRKyo00ROe7sKrO_KDBZWqKOeU,14237
16
+ yonder_cli_skill/references/api-contract.md,sha256=6wtlsBQGMqCzqe-5Tjr3WwgFpmVMBiVrV05ibg0rlSk,14256
17
+ yonder_cli_skill/references/local-ytdlp-security.md,sha256=8ehXPFzyvt_SkU8MUmnp6ZpXF7DtI7GrWCN9tpFkcD4,4441
18
+ yonder_cli_skill/scripts/check_setup.py,sha256=qU8DpiS7xpX7spatr0iHAeQ8ZC5GBerAs0a5whaDGPs,12507
19
+ yonder_cli_skill/scripts/setup-python.ps1,sha256=a_Ppyi-9gzoVwAFMXa3XCXtEy_mWojGar52X0uLS4zo,10802
20
+ yonder_cli_skill/scripts/setup-python.sh,sha256=JS9p53tS7kabJT-VTdpW7nRd3bSnJmO7hxMFfXFW1fs,7652
21
+ 5mghost_yonder-0.4.0.dist-info/METADATA,sha256=dQ0k7riXR3BjibmmhO2Slv8vhYiusnc3ytQnIb-PY6Y,2798
22
+ 5mghost_yonder-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
23
+ 5mghost_yonder-0.4.0.dist-info/entry_points.txt,sha256=V6gWs--orkOm03vFf8PbWC5kOBuE0zRDK-EJ-827Blc,47
24
+ 5mghost_yonder-0.4.0.dist-info/top_level.txt,sha256=rEKLnQ2rEFZpBP33HU0szuHkJDvOC8TZScXtB41-g2A,28
25
+ 5mghost_yonder-0.4.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ yonder = yonder_cli.cli:main
@@ -0,0 +1,2 @@
1
+ yonder_cli
2
+ yonder_cli_skill
yonder_cli/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Standalone Yonder CLI package."""
2
+
3
+ __version__ = '0.4.0'
@@ -0,0 +1,397 @@
1
+ """Offline client authentication state machine; all external I/O is injected."""
2
+ from functools import wraps
3
+ import hashlib
4
+ import json
5
+ import re
6
+ import uuid
7
+
8
+ from storage import (FileBackend, FakeKeychain, Refused, require, token, MAX_HISTORY,
9
+ MAX_OUTBOX, safe_error)
10
+ from transport import AUTHORITY, credential, identity
11
+
12
+
13
+ SAFE_CODES = frozenset(('REAUTH_REQUIRED STORAGE_LOCKED STORAGE_DENIED STORAGE_UNAVAILABLE STORAGE_UNSUPPORTED '
14
+ 'STATE_INVALID STATE_UNSUPPORTED STATE_FULL STATE_CONFLICT COMMAND_INVALID COMMAND_CONFLICT '
15
+ 'ENVIRONMENT_INVALID ENVIRONMENT_AMBIGUOUS TRANSPORT_INVALID TRANSPORT_UNKNOWN TRANSPORT_BUSY '
16
+ 'IDENTITY_INVALID IDENTITY_CONFLICT AUTHENTICATION_REQUIRED LOGIN_STALE LOGIN_EXPIRED CALLBACK_INVALID '
17
+ 'REVOKE_QUEUE_FULL OPERATION_REFUSED authorization_pending slow_down expired_token access_denied invalid_grant ACCESS_DENIED').split())
18
+
19
+
20
+ MESSAGES = {
21
+ 'REAUTH_REQUIRED': 'Start a new manual login; an earlier request has an unknown outcome.',
22
+ 'STORAGE_LOCKED': 'Retry after the current operation releases the fixture lock.',
23
+ 'STORAGE_DENIED': 'Check the private fixture storage permissions.',
24
+ 'STORAGE_UNAVAILABLE': 'Inspect the fixture storage before retrying.',
25
+ 'STORAGE_UNSUPPORTED': 'Use an explicitly supported fixture backend.',
26
+ 'AUTHENTICATION_REQUIRED': 'Sign in again with a verified API Key.',
27
+ }
28
+
29
+
30
+ def public(fn):
31
+ @wraps(fn)
32
+ def wrapped(*args, **kwargs):
33
+ try:
34
+ return fn(*args, **kwargs)
35
+ except Refused as error:
36
+ raise Refused(error.code if type(error.code) is str and error.code in SAFE_CODES else 'OPERATION_REFUSED') from None
37
+ except Exception as error:
38
+ raise safe_error(error) from None
39
+ return wrapped
40
+
41
+
42
+ def error_result(error):
43
+ code = error.code if isinstance(error, Refused) and type(error.code) is str and error.code in SAFE_CODES else 'OPERATION_REFUSED'
44
+ return {'error': code, 'nextStep': MESSAGES.get(code, 'Inspect the fixture operation and retry manually.')}
45
+
46
+
47
+ def environment_key(entries):
48
+ # Explicit input only, never inspect the process's real environment.
49
+ require(type(entries) in (dict, list, tuple), 'ENVIRONMENT_INVALID')
50
+ pairs = list(entries.items()) if type(entries) is dict else entries
51
+ matches = []
52
+ for pair in pairs:
53
+ require(type(pair) in (list, tuple) and len(pair) == 2 and type(pair[0]) is str, 'ENVIRONMENT_INVALID')
54
+ if pair[0] == 'YONDER_API_KEY':
55
+ matches.append(pair[1])
56
+ require(len(matches) <= 1, 'ENVIRONMENT_AMBIGUOUS')
57
+ if matches:
58
+ require(token(matches[0]) and len(matches[0]) >= 8, 'ENVIRONMENT_INVALID')
59
+ return matches[0]
60
+ return None
61
+
62
+
63
+ class ClientAuth:
64
+ def __init__(self, *, backend, transport, clock, revoke, environment=()):
65
+ require(type(backend) in (FileBackend, FakeKeychain), 'STORAGE_UNSUPPORTED')
66
+ require(callable(clock) and callable(revoke) and all(callable(getattr(transport, k, None))
67
+ for k in ('issue', 'poll', 'current_identity', 'exchange')), 'TRANSPORT_INVALID')
68
+ self.backend, self.transport, self.clock, self.revoke = backend, transport, clock, revoke
69
+ self.env_key = environment_key(environment)
70
+ self.devices = {}
71
+
72
+ def _save(self, s):
73
+ s['revision'] += 1
74
+ self.backend.write(s)
75
+
76
+ def _command(self, s, command, payload):
77
+ require(token(command), 'COMMAND_INVALID')
78
+ fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
79
+ previous = next((row for row in s['commands'] if row['id'] == command), None)
80
+ if previous:
81
+ require(previous['fingerprint'] == fingerprint, 'COMMAND_CONFLICT')
82
+ return previous, True
83
+ require(len(s['commands']) < MAX_HISTORY, 'STATE_FULL')
84
+ row = dict(id=command, fingerprint=fingerprint, result={'status': 'pending'})
85
+ s['commands'].append(row)
86
+ return row, False
87
+
88
+ def _intent(self, s, identifier, kind):
89
+ require(len(s['intents']) < MAX_HISTORY, 'STATE_FULL')
90
+ row = dict(id=identifier, kind=kind, epoch=s['epoch'], status='pending')
91
+ require(not any(item['id'] == identifier for item in s['intents']), 'COMMAND_CONFLICT')
92
+ s['intents'].append(row)
93
+ return row
94
+
95
+ def _enqueue(self, s, key_id, status='ready'):
96
+ if any(item['keyId'] == key_id for item in s['outbox']):
97
+ return
98
+ require(len(s['outbox']) < MAX_OUTBOX, 'REVOKE_QUEUE_FULL')
99
+ s['outbox'].append(dict(id=uuid.uuid4().hex, keyId=key_id, attempts=0, status=status))
100
+
101
+ def _reserve(self, s, command):
102
+ # Account for the active credential's eventual revoke as well as every
103
+ # in-flight/unknown candidate. A new epoch never frees a reservation.
104
+ active = s['credential'] and not any(i['keyId'] == s['credential']['id'] for i in s['outbox'])
105
+ require(len(s['outbox']) + (1 if active else 0) < MAX_OUTBOX, 'REVOKE_QUEUE_FULL')
106
+ require(not any(i['id'] == command for i in s['outbox']), 'COMMAND_CONFLICT')
107
+ s['outbox'].append(dict(id=command, keyId=None, attempts=0, status='reserved'))
108
+
109
+ def _call(self, fn, *args):
110
+ try:
111
+ return fn(*args)
112
+ except Refused as error:
113
+ raise Refused(error.code if type(error.code) is str and error.code in SAFE_CODES else 'TRANSPORT_UNKNOWN') from None
114
+ except Exception:
115
+ raise Refused('TRANSPORT_UNKNOWN') from None
116
+
117
+ @public
118
+ def login(self, command, *, cloud_ai=False, ssh=False, browser_available=False, reauth=False):
119
+ require(all(type(v) is bool for v in (cloud_ai, ssh, browser_available, reauth)), 'COMMAND_INVALID')
120
+ mode = 'browser' if browser_available and not cloud_ai and not ssh else 'device'
121
+ with self.backend.locked():
122
+ s = self.backend.read()
123
+ row, replay = self._command(s, command, ['login', mode, reauth])
124
+ if replay:
125
+ return dict(row['result'])
126
+ unresolved = [i for i in s['intents'] if i['status'] == 'pending']
127
+ require(not unresolved or reauth, 'REAUTH_REQUIRED')
128
+ for item in unresolved:
129
+ item['status'] = 'needs-attention'
130
+ for item in s['outbox']:
131
+ if item['status'] == 'held':
132
+ item['status'] = 'ready'
133
+ elif item['status'] == 'reserved':
134
+ item['status'] = 'unknown'
135
+ s['epoch'] += 1
136
+ transaction, state = uuid.uuid4().hex, uuid.uuid4().hex
137
+ s['slot'] = dict(transaction=transaction, state=state, epoch=s['epoch'], mode=mode, command=command)
138
+ result = dict(status='login-pending', mode=mode, transaction=transaction, state=state)
139
+ row['result'] = result
140
+ self._save(s)
141
+ return dict(result)
142
+
143
+ @public
144
+ def device_start(self, transaction):
145
+ require(token(transaction), 'CALLBACK_INVALID')
146
+ intent_id = uuid.uuid4().hex
147
+ with self.backend.locked():
148
+ s = self.backend.read()
149
+ slot = s['slot']
150
+ require(slot and slot['transaction'] == transaction and slot['mode'] == 'device', 'LOGIN_STALE')
151
+ require(not any(i['epoch'] == s['epoch'] and i['kind'] == 'issue' for i in s['intents']), 'REAUTH_REQUIRED')
152
+ self._intent(s, intent_id, 'issue')
153
+ epoch = s['epoch']
154
+ self._save(s)
155
+ try:
156
+ data = self._call(self.transport.issue)
157
+ require(type(data) is dict and set(data) <= {'device_code', 'user_code', 'verification_uri', 'verification_uri_complete', 'expires_in', 'interval'} and
158
+ {'device_code', 'user_code', 'verification_uri', 'expires_in', 'interval'} <= set(data), 'TRANSPORT_INVALID')
159
+ require(token(data['device_code']) and type(data['user_code']) is str and
160
+ re.fullmatch(r'[A-Z0-9-]{4,20}', data['user_code']) is not None and
161
+ data['verification_uri'] == AUTHORITY + '/auth/device' and
162
+ type(data['expires_in']) is int and 1 <= data['expires_in'] <= 600 and
163
+ type(data['interval']) is int and 1 <= data['interval'] <= 60, 'TRANSPORT_INVALID')
164
+ if 'verification_uri_complete' in data:
165
+ require(data['verification_uri_complete'] == AUTHORITY + '/auth/device?user_code=' + data['user_code'], 'TRANSPORT_INVALID')
166
+ except Refused:
167
+ raise Refused('REAUTH_REQUIRED') from None
168
+ with self.backend.locked():
169
+ s = self.backend.read()
170
+ item = next(i for i in s['intents'] if i['id'] == intent_id)
171
+ item['status'] = 'done'
172
+ if s['epoch'] != epoch or not s['slot'] or s['slot']['transaction'] != transaction:
173
+ self._save(s)
174
+ raise Refused('LOGIN_STALE')
175
+ self._save(s)
176
+ self.devices[transaction] = dict(code=data['device_code'], interval=data['interval'],
177
+ next=self.clock() + data['interval'], deadline=self.clock() + data['expires_in'], epoch=epoch)
178
+ return dict(status='human-approval-required', verificationUri=data['verification_uri'],
179
+ userCode=data['user_code'], instruction='Open the verified address and approve this device manually.',
180
+ nextPollAt=self.devices[transaction]['next'], deadline=self.devices[transaction]['deadline'])
181
+
182
+ def _consume(self, command, transaction, mode, state=None):
183
+ require(token(transaction) and (state is None or token(state)), 'CALLBACK_INVALID')
184
+ with self.backend.locked():
185
+ s = self.backend.read()
186
+ row, replay = self._command(s, command, ['consume', transaction, mode, state])
187
+ if replay:
188
+ require(row['result']['status'] != 'pending', 'REAUTH_REQUIRED')
189
+ return dict(row['result'])
190
+ slot = s['slot']
191
+ require(slot and slot['transaction'] == transaction and slot['mode'] == mode, 'LOGIN_STALE')
192
+ require(mode != 'browser' or state == slot['state'], 'CALLBACK_INVALID')
193
+ require(not any(i['status'] == 'pending' and i['epoch'] == s['epoch'] for i in s['intents']), 'REAUTH_REQUIRED')
194
+ if mode == 'device':
195
+ device = self.devices.get(transaction)
196
+ require(device and device['epoch'] == s['epoch'], 'REAUTH_REQUIRED')
197
+ require(self.clock() < device['deadline'], 'LOGIN_EXPIRED')
198
+ if self.clock() < device['next']:
199
+ row['result'] = {'status': 'wait', 'nextPollAt': device['next'], 'deadline': device['deadline']}
200
+ self._save(s)
201
+ return dict(row['result'])
202
+ self._intent(s, command, 'consume' if mode == 'device' else 'callback')
203
+ self._reserve(s, command)
204
+ epoch = s['epoch']
205
+ self._save(s)
206
+ slow_delay = None
207
+ try:
208
+ data = self._call(self.transport.poll, device['code']) if mode == 'device' else self._call(self.transport.exchange, transaction, state)
209
+ if mode == 'device' and type(data) is dict and data.get('error') == 'slow_down' and set(data) <= {'error', 'interval'}:
210
+ delay = data.get('interval')
211
+ require(type(delay) is int and device['interval'] < delay <= 60, 'TRANSPORT_INVALID')
212
+ slow_delay = delay
213
+ raise Refused('slow_down')
214
+ issued = credential(data)
215
+ except Refused as error:
216
+ if error.code in ('expired_token', 'access_denied', 'invalid_grant') or mode == 'device' and error.code in ('authorization_pending', 'slow_down'):
217
+ with self.backend.locked():
218
+ s = self.backend.read()
219
+ next(i for i in s['intents'] if i['id'] == command)['status'] = 'done'
220
+ s['outbox'] = [i for i in s['outbox'] if i['id'] != command]
221
+ row = next(r for r in s['commands'] if r['id'] == command)
222
+ row['result'] = {'status': error.code}
223
+ if error.code in ('authorization_pending', 'slow_down'):
224
+ if error.code == 'slow_down':
225
+ device['interval'] = slow_delay if slow_delay is not None else min(device['interval'] + 5, 60)
226
+ device['next'] = self.clock() + device['interval']
227
+ row['result'].update(nextPollAt=device['next'], deadline=device['deadline'])
228
+ elif s['epoch'] == epoch:
229
+ s['slot'] = None
230
+ self._save(s)
231
+ return dict(row['result'])
232
+ with self.backend.locked():
233
+ s = self.backend.read()
234
+ next(i for i in s['outbox'] if i['id'] == command)['status'] = 'unknown'
235
+ self._save(s)
236
+ raise Refused('REAUTH_REQUIRED') from None
237
+ # A known issued Key must remain recoverable before another request,
238
+ # even if identity verification or the subsequent process is lost.
239
+ with self.backend.locked():
240
+ s = self.backend.read()
241
+ require(not any(i['keyId'] == issued['id'] for i in s['outbox']) and
242
+ (not s['credential'] or s['credential']['id'] != issued['id']), 'TRANSPORT_INVALID')
243
+ reservation = next(i for i in s['outbox'] if i['id'] == command)
244
+ require(reservation['status'] in ('reserved', 'unknown') and reservation['keyId'] is None, 'STATE_CONFLICT')
245
+ reservation.update(keyId=issued['id'], status='held')
246
+ self._save(s)
247
+ try:
248
+ user = identity(self._call(self.transport.current_identity, issued['key']))
249
+ except Refused:
250
+ with self.backend.locked():
251
+ s = self.backend.read()
252
+ next(i for i in s['intents'] if i['id'] == command)['status'] = 'done'
253
+ next(i for i in s['outbox'] if i['keyId'] == issued['id'])['status'] = 'ready'
254
+ next(r for r in s['commands'] if r['id'] == command)['result'] = {'status': 'identity-rejected'}
255
+ self._save(s)
256
+ raise Refused('AUTHENTICATION_REQUIRED') from None
257
+ with self.backend.locked():
258
+ s = self.backend.read()
259
+ next(i for i in s['intents'] if i['id'] == command)['status'] = 'done'
260
+ row = next(r for r in s['commands'] if r['id'] == command)
261
+ next(i for i in s['outbox'] if i['keyId'] == issued['id'])['status'] = 'ready'
262
+ if s['epoch'] != epoch or not s['slot'] or s['slot']['transaction'] != transaction:
263
+ row['result'] = {'status': 'login-stale'}
264
+ elif s['credential'] and s['credential']['userId'] != user['userId']:
265
+ row['result'] = {'status': 'identity-conflict'}
266
+ s['slot'] = None
267
+ else:
268
+ if s['credential']:
269
+ self._enqueue(s, s['credential']['id'])
270
+ # This candidate has become the active session, never revoke it
271
+ # through its pre-verification safety entry.
272
+ s['outbox'] = [i for i in s['outbox'] if i['keyId'] != issued['id']]
273
+ s['credential'] = {**issued, **user}
274
+ s['slot'] = None
275
+ row['result'] = {'status': 'signed-in'}
276
+ self._save(s)
277
+ self.devices.pop(transaction, None)
278
+ return dict(row['result'])
279
+
280
+ @public
281
+ def device_step(self, command, transaction):
282
+ return self._consume(command, transaction, 'device')
283
+
284
+ @public
285
+ def callback(self, command, transaction, state):
286
+ return self._consume(command, transaction, 'browser', state)
287
+
288
+ @public
289
+ def cancel(self, command, transaction):
290
+ require(token(transaction), 'CALLBACK_INVALID')
291
+ with self.backend.locked():
292
+ s = self.backend.read()
293
+ row, replay = self._command(s, command, ['cancel', transaction])
294
+ if replay:
295
+ return dict(row['result'])
296
+ require(s['slot'] and s['slot']['transaction'] == transaction, 'LOGIN_STALE')
297
+ s['epoch'] += 1
298
+ s['slot'] = None
299
+ row['result'] = {'status': 'cancelled'}
300
+ self._save(s)
301
+ self.devices.pop(transaction, None)
302
+ return {'status': 'cancelled'}
303
+
304
+ @public
305
+ def current_identity(self):
306
+ with self.backend.locked():
307
+ s = self.backend.read()
308
+ held = s['credential']
309
+ key = self.env_key or (held and held['key'])
310
+ epoch = s['epoch']
311
+ require(key, 'AUTHENTICATION_REQUIRED')
312
+ current = identity(self._call(self.transport.current_identity, key))
313
+ with self.backend.locked():
314
+ latest = self.backend.read()
315
+ require(self.env_key is not None or latest['epoch'] == epoch and latest['credential'] == held, 'LOGIN_STALE')
316
+ require(self.env_key is not None or current['userId'] == held['userId'], 'IDENTITY_CONFLICT')
317
+ return dict(current)
318
+
319
+ @public
320
+ def authorized_call(self, callback):
321
+ """Trusted, explicitly injected port. The credential never becomes a result.
322
+
323
+ Revalidate identity for every call and reject an in-flight logout or
324
+ credential replacement before exposing its response to a consumer.
325
+ """
326
+ require(callable(callback), 'TRANSPORT_INVALID')
327
+ with self.backend.locked():
328
+ state = self.backend.read()
329
+ held, epoch = state['credential'], state['epoch']
330
+ key = self.env_key or (held and held['key'])
331
+ require(key, 'AUTHENTICATION_REQUIRED')
332
+ current = identity(self._call(self.transport.current_identity, key))
333
+ require(self.env_key is not None or current['userId'] == held['userId'], 'IDENTITY_CONFLICT')
334
+ with self.backend.locked():
335
+ latest = self.backend.read()
336
+ require(latest['epoch'] == epoch and latest['credential'] == held, 'LOGIN_STALE')
337
+ response = self._call(callback, key, dict(current))
338
+ with self.backend.locked():
339
+ latest = self.backend.read()
340
+ require(latest['epoch'] == epoch and latest['credential'] == held, 'LOGIN_STALE')
341
+ # Even a faulty trusted fixture must not accidentally echo a Key.
342
+ try:
343
+ wire = json.dumps(response, ensure_ascii=False, allow_nan=False)
344
+ require(key not in wire, 'TRANSPORT_INVALID')
345
+ return json.loads(wire)
346
+ except (TypeError, ValueError):
347
+ raise Refused('TRANSPORT_INVALID') from None
348
+
349
+ @public
350
+ def logout(self, command):
351
+ with self.backend.locked():
352
+ s = self.backend.read()
353
+ row, replay = self._command(s, command, ['logout'])
354
+ if replay:
355
+ return dict(row['result'])
356
+ if s['credential']:
357
+ self._enqueue(s, s['credential']['id'])
358
+ s['epoch'] += 1
359
+ s['logoutEpoch'] = s['epoch']
360
+ for item in s['outbox']:
361
+ if item['status'] == 'held':
362
+ item['status'] = 'ready'
363
+ s['credential'], s['slot'] = None, None
364
+ row['result'] = dict(status='signed-out', environmentConfigured=self.env_key is not None,
365
+ revokePending=any(i['status'] != 'done' for i in s['outbox']))
366
+ self._save(s)
367
+ self.devices.clear()
368
+ return dict(row['result'])
369
+
370
+ @public
371
+ def drain_revoke(self):
372
+ # Keep the one owner lock across this bounded fixture request. Another
373
+ # process cannot mistake an active sending operation for crash recovery.
374
+ with self.backend.locked():
375
+ s = self.backend.read()
376
+ for item in s['outbox']:
377
+ if item['status'] == 'sending':
378
+ item['status'] = 'needs-attention'
379
+ item = next((i for i in s['outbox'] if i['status'] == 'ready'), None)
380
+ if item is None:
381
+ self._save(s)
382
+ return {'status': 'needs-attention' if any(i['status'] in ('reserved', 'unknown', 'held', 'needs-attention') for i in s['outbox']) else 'drained'}
383
+ item['status'], item['attempts'] = 'sending', item['attempts'] + 1
384
+ key_id = item['keyId']
385
+ self._save(s)
386
+ try:
387
+ reply = self._call(self.revoke, key_id)
388
+ require(type(reply) is dict and set(reply) == {'success'} and type(reply['success']) is bool, 'TRANSPORT_UNKNOWN')
389
+ outcome = 'done' if reply['success'] else 'ready'
390
+ except Refused:
391
+ outcome = 'needs-attention'
392
+ # Re-read after the request; the same flock still owns the record.
393
+ s = self.backend.read()
394
+ item = next(i for i in s['outbox'] if i['keyId'] == key_id)
395
+ item['status'] = 'needs-attention' if outcome == 'ready' and item['attempts'] >= 3 else outcome
396
+ self._save(s)
397
+ return {'status': 'revoke-confirmed' if item['status'] == 'done' else item['status']}