Walkthrough
- Information. The system lists its executors with
GET https://daas.masnet.com/api/v1/integrations/data/mp-gateway/executorsand sees whether they are available and whether their portal session is open. - Decision. With the session closed, it opens it with a session flow. To bid, it computes the SHA-256 of the manifest it will serve.
- Action. It creates a
PREPARE_BIDintent with that hash. Masnet wakes the executor and hands it a signed capability. The extension downloads the manifest and attachments from<data_plane_origin>/masnet-gateway/v1, verifies their integrity, checks that the portal session belongs to the company and loads the draft up to the Confirmation, without publishing. - Result. Your server receives the evidence of what the portal shows, line by line, and its digest. Masnet stores only a minimal acknowledgment. If the evidence matches your bid, the system requests
PUBLISH_BIDbound to that preparation, or a person publishes the draft in the portal.
Requirements in Masnet
- A company with a verified tax ID in Masnet.
- A production integration with the
read:mp_gatewayandwrite:mp_gatewayscopes. Atestintegration only receivesread:mp_gateway: it does not write to Mercado Público or open sessions. - The
mp_gatewaydomain grant, given by an administrator with a second factor in Company › Integrations: the server origin (data_plane_origin, required only withPREPARE_BIDorPUBLISH_BID), the allowed actions (allowed_actions), the declarants authorized for the sworn statement (allowed_declarant_ruts), the national IDs authorized to sign in (allowed_login_ruts) and, if the organization requires it, origin pinning through Chrome policy (require_managed_origin_pin). - At least one Chrome executor paired with the integration. An administrator creates the pairing code (valid for 120 s, shown once) and enters it on the pairing page of the Masnet extension on that computer. Up to 10 executors per integration and 25 per company.
- The granted action is the only gate: there are no separate flags to publish or to sign in. Changing the origin, adding
PUBLISH_BID,SESSION_LOGINor a purchase order action, or adding a national ID to the lists is an expansion and requires a recent second factor and explicit confirmation.
The client authenticates as in the rest of the Data API (OAuth 2.0 client_credentials or an mk_live_ key). The current per minute quotas apply; there are no hourly or daily caps.
Server address
data_plane_origin is the HTTPS origin of your server, for example https://mp-connector.empresa-ejemplo.cl. It must match the pattern ^https://[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+(:(443|102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$:
- Lowercase, your own domain name with at least one dot, port 443 or 1024 to 65535, no path, query or user.
- Masnet, Mercado Público, ChileCompra and ClaveÚnica domains, literal IP addresses in any notation and special-use names (
localhost,local,internal,svc,test,invalid,example,onion) are not accepted. - The name must resolve to a public address with a public certificate. A server on the company private network or on the same machine (
loopback_http) is not available yet: it depends on how Chrome treats the local network from an extension, which Masnet is measuring. Meanwhile, Masnet rejects those origins withMP_DIRECT_ORIGIN_FORBIDDEN. - Only an administrator with a second factor sets the origin, and it never travels in an intent.
Integrations API of the domain
Base: https://daas.masnet.com/api/v1/integrations/data/mp-gateway. Every response carries Cache-Control: no-store.
| Method | Path | Scope | Use |
|---|---|---|---|
GET | /data/mp-gateway/executors | read:mp_gateway | Executors of the integration with availability, session_state, session_epoch, session_login_supported and verified_rut. |
POST | /data/mp-gateway/executors/{executorId}/wake | read:mp_gateway | Wakes the executor and holds its connection for 150 s. |
POST | /data/mp-gateway/intents | The action's scope | Creates a durable intent. Answers 202 with intent_id and status_url. Idempotent by client_request_id. |
GET | /data/mp-gateway/intents/{intentId} | read:mp_gateway | Status and acknowledgment of the intent. Accepts Prefer: wait=N (N from 1 to 20 seconds): answers earlier if the intent changes. |
GET | /data/mp-gateway/intents/by-request/{clientRequestId} | read:mp_gateway | Recovers the intent after a network failure, with the client_request_id you generated. |
POST | /data/mp-gateway/intents/{intentId}/cancel | The action's scope | Queued, it cancels it. Running, it flags it so the extension aborts before the next submission to the portal. |
The session flow routes are in its guide.
Actions
| Action | Scope | Portal session | What it does |
|---|---|---|---|
SESSION_STATUS | read:mp_gateway | Any | Confirms the state of the portal session on the executor. |
SESSION_LOGIN | write:mp_gateway | Closed | Opens the portal session. It is not an intent: it is a session flow (guide). |
CHANGE_ORGANIZATION | write:mp_gateway | Active | Changes the active organization of the session (organization_code). |
SESSION_LOGOUT | write:mp_gateway | Any | Closes the portal session on the executor. |
READ_SNAPSHOT | read:mp_gateway | Active | Reads the state of a tender in the portal: status, bids and attachments. |
READ_SII_REPRESENTATIVES | read:mp_gateway | Active | Reads the current legal representatives the portal shows for the sworn statement. |
PREPARE_BID | write:mp_gateway | Active | Loads the bid as a draft up to the Confirmation, without publishing. |
PUBLISH_BID | write:mp_gateway | Active | Publishes a draft prepared by the same executor, after re-reading the Confirmation. |
READ_PURCHASE_ORDER_STATE | read:mp_gateway | Active | Reads the live state of a purchase order in the portal and the actions it admits. |
PURCHASE_ORDER_ACCEPT | write:mp_gateway | Active | Accepts a purchase order. |
PURCHASE_ORDER_REJECT | write:mp_gateway | Active | Rejects a purchase order with a portal reason. |
PURCHASE_ORDER_REQUEST_CANCELLATION | write:mp_gateway | Active | Requests the cancellation of an accepted purchase order, with a portal reason. |
PURCHASE_ORDER_ACCEPT_BUYER_CANCELLATION | write:mp_gateway | Active | Accepts the cancellation the buyer requested. |
PURCHASE_ORDER_REJECT_BUYER_CANCELLATION | write:mp_gateway | Active | Rejects the cancellation the buyer requested. |
Each intent carries client_request_id (a UUID v4 you generate), executor_id, action and job_ref: the opaque identifier of the job on your server, which the extension uses in the data plane routes. Repeating the same client_request_id with the same body returns the same intent; with another body, 409 MP_DIRECT_IDEMPOTENCY_CONFLICT.
POST https://daas.masnet.com/api/v1/integrations/data/mp-gateway/intents
Authorization: Bearer <token>
Content-Type: application/json
{
"client_request_id": "11111111-1111-4111-8111-111111111111",
"executor_id": "22222222-2222-4222-8222-222222222222",
"action": "PREPARE_BID",
"tender_code": "3479-61-LR26",
"job_ref": "erp-bid-2026-00412",
"manifest_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"document_count": 4,
"total_document_bytes": 2450120,
"stop_before_publish": true
}Intent states
status | Meaning |
|---|---|
queued | Queued. If no executor takes it within 90 s, it becomes expired with no effect. |
running | An executor took it, with a 45 s lease renewed every 15 s. |
succeeded | Finished well. summary carries the minimal acknowledgment. |
failed | Finished without the requested effect. error_code says why and effects_applied whether anything was written. |
uncertain | The lease was lost during an effect on the portal (effects_applied = possible). Never retried automatically: reconcile with READ_SNAPSHOT before repeating. |
cancelled | Cancelled by your system or when the executor was revoked. |
expired | Expired in the queue with no effect. |
Query GET https://daas.masnet.com/api/v1/integrations/data/mp-gateway/intents/{intentId} with Prefer: wait=20: the response arrives as soon as the intent changes, or after 20 seconds without changes. After a network failure, recover the intent with GET https://daas.masnet.com/api/v1/integrations/data/mp-gateway/intents/by-request/{clientRequestId}.
Executor availability
availability | Meaning and what to do |
|---|---|
ready | Active session with the company verified tax ID: receives intents. |
session_closed | No portal session. With SESSION_LOGIN granted, open it with a session flow; otherwise a person opens it in that Chrome. |
session_unverifiable | The session proof did not conclude. It retries by itself; query again. |
company_blocked | The session belongs to another company. Send CHANGE_ORGANIZATION or a person switches company in the portal. |
busy | It has an active intent or session flow. Wait until it ends. |
offline | No recent presence. Wake it with POST .../wake. |
paused | An administrator paused it in Company › Integrations. |
update_required | The extension on the Chrome executor is below the contract minimum version (1.2.2). |
revoked | The link was revoked. The Chrome must be paired again. |
An executor serves one intent or session flow at a time. A company has at most one active PREPARE_BID or PUBLISH_BID per tender, also against bids a person prepares from Masnet: another answers 409 MP_DIRECT_TENDER_BUSY. The same applies to a purchase order: one active action at a time, also against those a person performs from Masnet (409 MP_DIRECT_PURCHASE_ORDER_BUSY).
The five endpoints of your server
Under <data_plane_origin>/masnet-gateway/v1. The extension waits at most the time shown and does not follow redirects: a 3xx aborts with MP_DIRECT_REDIRECT_BLOCKED.
| Method | Path | Use | Maximum wait |
|---|---|---|---|
GET | /masnet-gateway/v1/health | Connectivity, TLS and CORS. No token. | 10 s |
GET | /masnet-gateway/v1/jobs/{jobRef}/manifest | PREPARE_BID manifest, up to 1 MiB. It is the only action with a manifest. | 15 s |
GET | /masnet-gateway/v1/jobs/{jobRef}/documents/{docId} | One attachment, up to 15 MiB, with X-Document-Sha256 and Content-Length. | 120 s |
POST | /masnet-gateway/v1/jobs/{jobRef}/progress | Progress, at most one every 2 s. Answer 204. A failure here never stops the bid. | 5 s |
POST | /masnet-gateway/v1/jobs/{jobRef}/result | Full result, up to 4 MiB, with Idempotency-Key: <intent_id>. Answer 200 with the acknowledgment. | 30 s |
The data plane has no sign-in endpoint: the extension never asks your server for credentials. Requests go out with credentials: omit, redirect: error, cache: no-store and referrerPolicy: no-referrer.
Verify the token
Every request to the /jobs/... routes carries Authorization: Bearer <token>: a compact JWS signed by Masnet with Ed25519 (alg: EdDSA, typ: mp-gateway-dataplane+jwt, kid), valid for 60 s and renewed with each lease. The public keys are at https://daas.masnet.com/api/v1/integrations/public/mp-gateway/jwks.json (up to 8 keys; store them by kid and read the JWKS again on an unknown kid).
- Valid Ed25519 signature with the
kidkey,alg = EdDSAandtyp = mp-gateway-dataplane+jwt. issishttps://daas.masnet.com(orhttps://dev-daas.masnet.comin development),audis exactly yourdata_plane_originandexpis current, with a tolerance of 5 s or less.subisintegration:<your integration_id>,company_idis your company andexecutor_idis one of your executors.job_refis the one in the path andintent_idis the one you received when creating the intent for thatjob_ref.use = jobis valid for any job route.use = result_deliveryis valid only forPOST /masnet-gateway/v1/jobs/{jobRef}/result: reject it on any other.
| Claim | Required | Rule | Use |
|---|---|---|---|
v | Yes | 1 | Claims version. |
iss | Yes | https://daas.masnet.com, https://dev-daas.masnet.com | Issuer: the Masnet plane. |
aud | Yes | Text matching ^https://[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+(:(443|102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$ or Text matching ^http://(127\.0\.0\.1|localhost):(102[4-9]|10[3-9][0-9]|1[1-9][0-9]{2}|[2-9][0-9]{3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$ | Your exact data_plane_origin. |
sub | Yes | Text matching ^integration:[0-9a-f-]{36}$ | integration:<integration_id>. |
jti | Yes | Text matching ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ | Unique token identifier. |
iat | Yes | Integer from 1700000000 | Issued at (Unix seconds). |
exp | Yes | Integer from 1700000001 | Expires at (Unix seconds). |
company_id | Yes | Integer from 1 | Company in Masnet. |
integration_id | Yes | Text matching ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ | Your integration. |
executor_id | Yes | Text matching ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ | Calling executor. |
intent_id | Yes | Text matching ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ | Running intent. |
action | Yes | SESSION_STATUS, SESSION_LOGIN, CHANGE_ORGANIZATION, SESSION_LOGOUT, READ_SNAPSHOT, READ_SII_REPRESENTATIVES, PREPARE_BID, PUBLISH_BID, READ_PURCHASE_ORDER_STATE, PURCHASE_ORDER_ACCEPT, PURCHASE_ORDER_REJECT, PURCHASE_ORDER_REQUEST_CANCELLATION, PURCHASE_ORDER_ACCEPT_BUYER_CANCELLATION, PURCHASE_ORDER_REJECT_BUYER_CANCELLATION | Intent action. |
job_ref | Yes | Text matching ^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$ | Job on your server. |
tender_code | No | Text matching ^[0-9]+-[0-9]+-[A-Z0-9]+$ | Tender, in actions that have one. |
use | Yes | job, result_delivery | job or result_delivery. |
Answer 401 without detail if any check fails. CORS does not authenticate: a process that is not a browser ignores it, and access control is this token.
CORS
The fetch comes from the extension service worker. Your server must send these headers on every response, including the OPTIONS preflight and errors:
| Header | Value |
|---|---|
Access-Control-Allow-Origin | chrome-extension://icghfhpbiebbbocbheaieofjadfnlmgg |
Access-Control-Allow-Methods | GET, POST, OPTIONS |
Access-Control-Allow-Headers | Authorization, Content-Type, X-Masnet-Intent-Id, X-Masnet-Device-Id, X-Masnet-Job-Ref, Idempotency-Key |
Access-Control-Expose-Headers | X-Document-Sha256, Content-Type, Content-Length, Retry-After |
Vary | Origin |
Cache-Control | no-store |
Access-Control-Allow-Credentials | Do not send it. |
chrome-extension://icghfhpbiebbbocbheaieofjadfnlmggis the origin of the extension published in the Chrome Web Store. Never answer*.- The extension may send
X-Masnet-Intent-Id,X-Masnet-Device-Id,X-Masnet-Job-RefandIdempotency-Key. Allow them in the preflight; authorization is decided only by the token.
Manifest and attachments
manifest_sha256 is the lowercase hexadecimal SHA-256 of the exact bytes your server will return in GET /masnet-gateway/v1/jobs/{jobRef}/manifest. The extension hashes the received body, compares it with the one signed in the capability and only then parses it as JSON. There is no canonicalization: store the bytes you will serve, hash them and send the hash in the intent. A difference aborts with MP_DIRECT_MANIFEST_MISMATCH before touching the portal.
{
"contract_version": "mp-gateway-direct-bid.v1",
"action": "PREPARE_BID",
"tender_code": "3479-61-LR26",
"bid_type": "STANDARD",
"bid_name": "Oferta Técnica y Económica Insumos Médicos",
"bid_description": "Propuesta completa conforme a bases administrativas y técnicas.",
"currency": "CLP",
"is_utp": false,
"stop_before_publish": true,
"products": [
{
"item_line": 1,
"product_info": "Guante de nitrilo talla M caja x100",
"quantity": 500,
"unit_measure": "CAJA",
"unit_price": 4250,
"supplier_comment": "Stock inmediato, registro ISP vigente.",
"is_offered": true
}
],
"documents": [
{
"doc_id": "anexo-1-firmado",
"file_name": "Anexo_1_Identificacion_Firmado_FEA.pdf",
"type": "ADMIN",
"action": "upload",
"content_type": "application/pdf",
"size_bytes": 184320,
"sha256": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
"externally_signed": true
}
],
"affidavit": {
"declarant_rut": "12.345.678-9",
"declarant_name": "Juan Pérez González",
"legal_address": "Av. Apoquindo 4500, Las Condes, Santiago",
"declarant_type": 1,
"is_rep_sii": true,
"sign_type": "FS",
"answers": [
{
"id": 1,
"answer": true
},
{
"id": 10,
"answer": false
}
]
}
}| Field | Required | Rule | Use |
|---|---|---|---|
contract_version | Yes | "mp-gateway-direct-bid.v1" | Manifest version. |
action | Yes | "PREPARE_BID" | Only PREPARE_BID has a manifest. |
tender_code | Yes | Text matching ^[0-9]+-[0-9]+-[A-Z0-9]+$ | Must be the intent tender; if it differs, the extension aborts with MP_DIRECT_MANIFEST_MISMATCH. |
offers_url | No | Text matching ^https://www\.mercadopublico\.cl/ | Address of the bid in the portal, if known. |
mp_bid_id | No | Text matching ^[1-9][0-9]{0,18}$ | Existing portal draft to edit, if any. |
bid_type | Yes | STANDARD, ALTERNATIVE | Standard or alternative bid. |
bid_name | Yes | Text, 2 to 250 characters | Bid name. |
bid_description | Yes | Text, 1 to 4000 characters | Bid description. |
currency | Yes | "CLP" | Chilean pesos only in version 1. |
is_utp | Yes | Boolean | Bid by a temporary union of suppliers. |
utp_id | No | Text matching ^[1-9][0-9]{0,18}$ | Temporary union identifier, with is_utp. |
stop_before_publish | Yes | true | Always true: preparation stops before publishing. |
expected_supplier_ruts | No | Array, 1 to 10 | Normalized tax IDs you expect in the portal session. |
products | Yes | Array, 1 to 2000 | Bid lines. |
documents | Yes | Array, 0 to 100 | Attachments to upload, keep or delete. |
affidavit | Yes | Object | Sworn statement data. |
Lines
| Field | Required | Rule | Use |
|---|---|---|---|
item_line | Yes | Integer from 1 up to 10000 | Tender line number. |
product_info | No | Text, 0 to 500 characters | Description of the offered product. |
buyer_info | No | Text, 0 to 500 characters | Buyer description, for reference. |
code_onu | No | Text matching ^[0-9]{4,16}$ | UN product code. |
quantity | Yes | Number greater than 0 | Offered quantity. |
unit_measure | No | Text, 1 to 32 characters | Unit of measure. |
unit_price | Yes | Number from 0 | Net unit price in pesos. |
supplier_comment | No | Text, 0 to 2000 characters | Supplier comment. |
currency | No | "CLP" | Chilean pesos only. |
is_offered | Yes | Boolean | false leaves the line unoffered. |
Attachments
| Field | Required | Rule | Use |
|---|---|---|---|
doc_id | Yes | Text matching ^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$ | Identifier the extension uses in GET /masnet-gateway/v1/jobs/{jobRef}/documents/{docId}. |
file_name | Yes | Text, 1 to 200 characters | Name it is uploaded with. |
type | Yes | ADMIN, TEC, ECO, LOCAL | Portal section: administrative, technical, economic or local. |
action | Yes | upload, keep, delete | upload uploads the file; keep keeps one already loaded (portal_file_id); delete removes it. |
content_type | No | Text, 3 to 128 characters | File type. |
size_bytes | No | Integer from 1 up to 15728640 | Exact size in bytes. Required for upload. |
sha256 | No | Text matching ^[0-9a-f]{64}$ | Lowercase hexadecimal SHA-256 of the bytes you will serve. Required for upload. |
portal_file_id | No | Text, 1 to 128 characters | File already in the portal, for keep and delete. |
externally_signed | No | Boolean | The file arrives signed by the legal representative with the company signing solution. |
- Before uploading each attachment, the extension checks the exact size and the SHA-256 against the manifest and against the
Content-LengthandX-Document-Sha256headers. A difference aborts withMP_DIRECT_DOCUMENT_MISMATCH. Up to 100 attachments and 150 MiB per bid; the intentdocument_countandtotal_document_bytesmust match the manifest. - Attachments that need the legal representative signature arrive signed from the company infrastructure (
externally_signed). No binary or signing key leaves your network toward Masnet.
Sworn statement
| Field | Required | Rule | Use |
|---|---|---|---|
declarant_rut | Yes | Text matching ^[0-9]{1,2}\.?[0-9]{3}\.?[0-9]{3}-[0-9Kk]$ | Declarant tax ID. Must be among the authorized declarants of the grant. |
declarant_name | Yes | Text, 2 to 200 characters | Declarant name. |
legal_address | Yes | Text, 4 to 300 characters | Legal address. |
declarant_type | Yes | 1, 2 | Declarant type the portal asks for. |
is_rep_sii | Yes | Boolean | The declarant is listed as a representative at the SII. |
sign_type | No | FS | Portal signature type. |
answers | No | Array, 1 to 30 | Sworn statement answers by question number. |
The extension signs the portal sworn statement only if declarant_rut, normalized, is among the authorized declarants of the grant. Otherwise it answers MP_DIRECT_DECLARANT_NOT_GRANTED and does not sign. You can read the current representatives beforehand with READ_SII_REPRESENTATIVES.
Result and observed evidence
When it finishes, the extension sends the full result to POST /masnet-gateway/v1/jobs/{jobRef}/result with Idempotency-Key: <intent_id> and up to 3 retries (after 2, 5 and 10 s). Answer 200 with { "received": true, "intent_id": "...", "replayed": false }, and replayed: true if you already had that result.
| Field | Required | Rule | Use |
|---|---|---|---|
intent_id | Yes | Text matching ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ | Intent it belongs to. It is also the Idempotency-Key. |
action | Yes | SESSION_STATUS, SESSION_LOGIN, CHANGE_ORGANIZATION, SESSION_LOGOUT, READ_SNAPSHOT, READ_SII_REPRESENTATIVES, PREPARE_BID, PUBLISH_BID, READ_PURCHASE_ORDER_STATE, PURCHASE_ORDER_ACCEPT, PURCHASE_ORDER_REJECT, PURCHASE_ORDER_REQUEST_CANCELLATION, PURCHASE_ORDER_ACCEPT_BUYER_CANCELLATION, PURCHASE_ORDER_REJECT_BUYER_CANCELLATION | Executed action. |
outcome | Yes | succeeded, failed, uncertain | Outcome: succeeded, failed or uncertain. |
effects_applied | Yes | none, possible, confirmed | none, possible or confirmed. |
error_code | No | Text matching ^[A-Z][A-Z0-9_]{1,127}$ or null | MP_DIRECT_* code if it failed. |
error_message | No | Text, 0 to 500 characters | Sanitized message, without portal data. |
observed_bid | No | Object | Preparation evidence (PREPARE_BID). |
receipt | No | Object | Publication receipt (PUBLISH_BID). |
session | No | Object | Session state, in session actions. |
sii_representatives | No | Array, 0 to 100 | Representatives read (READ_SII_REPRESENTATIVES). |
snapshot | No | Object | Tender reading (READ_SNAPSHOT). |
finished_at | Yes | Text, 20 to 40 characters | Finish time. |
In PREPARE_BID, observed_bid.observed is the evidence of what the portal Confirmation shows (BidObservedMaterial version 1): quantity, unit price and total per line as canonical decimals, the grand total as an exact sum and the signed sworn statement. observed_sha256 is the SHA-256 of the UTF-8 bytes of that object serialized without spaces and with keys sorted by UTF-16 code unit. Masnet receives only the digest, never the evidence.
{
"version": 1,
"currency": "CLP",
"lines": [
{
"line": 1,
"quantity": "10",
"unitPrice": "1250.5",
"total": "12505",
"currency": "CLP"
},
{
"line": 2,
"quantity": "3",
"unitPrice": "990",
"total": "2970",
"currency": "CLP"
}
],
"total": "15475",
"affidavitSigned": true
}- Recompute the digest on your server and compare each line with your own bid. That comparison is what authorizes requesting
PUBLISH_BID. - The object holds only strings, integers, booleans, arrays and objects: any language reproduces the serialization. Decimals are strings without sign or trailing zeros (
1250.5, not1250.50). - Masnet stores only the acknowledgment:
mp_bid_id,observed_sha256,affidavit_signed,document_count_uploadedanddata_plane_delivery_ok(at most 32 KiB).
Publish
- Your system sends
PUBLISH_BIDwithprepare_intent_id,mp_bid_idandexpected_observed_sha256from the preparation. - Masnet checks that the preparation is from the same executor and integration, ended as
succeededand matches tender, draft and digest. Otherwise,409 MP_DIRECT_PREPARE_REQUIRED. - The extension re-reads the Confirmation and compares it with the stored evidence. If it differs, it answers
MP_DIRECT_OBSERVED_MISMATCHand does not publish. - It publishes, captures the receipt and delivers it to your server in
receipt.
{
"client_request_id": "33333333-3333-4333-8333-333333333333",
"executor_id": "22222222-2222-4222-8222-222222222222",
"action": "PUBLISH_BID",
"tender_code": "3479-61-LR26",
"prepare_intent_id": "44444444-4444-4444-8444-444444444444",
"mp_bid_id": "78247815",
"expected_observed_sha256": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"job_ref": "erp-bid-2026-00412-pub"
}Purchase orders
With the same grant, your system manages in Mercado Público the purchase orders the company receives, from the same Chrome executor. Purchase orders do not use your server: there is no manifest, data plane token or result at data_plane_origin. The result comes back through Masnet, in the same intent.
- Information.
GET https://daas.masnet.com/api/v1/integrations/data/received-purchase-orders?status=1lists the received orders (scoperead:purchase_orders), with their Mercado Público state, their management and the actions the portal admits. AREAD_PURCHASE_ORDER_STATEintent reads the live state in the portal. - Decision. Your system chooses the action with the state it just read and sends it as
expected_status. - Action. It creates a
PURCHASE_ORDER_*intent withpo_code,expected_statusand, when the action requires it,reason_id. Masnet checks the action and the order, signs a capability bound to that order, action and state, and the extension performs the action in the portal. - Result.
summarycarriespo_code,po_status,po_status_labelandpo_observed_at. The action is recorded in the purchase order history in Masnet, with the integration as actor.
| Action | From state | Reason (reason_id) |
|---|---|---|
PURCHASE_ORDER_ACCEPT | 1 Sent to supplier, 2 In process | None |
PURCHASE_ORDER_REJECT | 1 Sent to supplier, 2 In process | 6, 7, 14, 17, 12 |
PURCHASE_ORDER_REQUEST_CANCELLATION | 4 Accepted | 3, 5, 15, 11 |
PURCHASE_ORDER_ACCEPT_BUYER_CANCELLATION | 3 Cancellation requested | None |
PURCHASE_ORDER_REJECT_BUYER_CANCELLATION | 3 Cancellation requested | None |
{
"client_request_id": "0b6f7a2c-1d3e-4f5a-8b9c-0d1e2f3a4b5c",
"executor_id": "8d1f2c4e-5b6a-4c7d-9e8f-0a1b2c3d4e5f",
"action": "PURCHASE_ORDER_ACCEPT",
"job_ref": "erp-oc-1",
"po_code": "999-5-SE26",
"expected_status": 1
}Before waking the executor, Masnet checks in this order:
- That the action is in
allowed_actionsof the grant and open in Masnet. Masnet opens to integrations the same actions it offers to people in Purchase orders; the others answer409 MP_DIRECT_ACTION_NOT_AVAILABLEwhen granted and when the intent is created. Granting them also requires theworkspace.purchase_orders.editpermission. - That the order was issued to the company verified tax ID. Otherwise,
404 MP_DIRECT_PURCHASE_ORDER_NOT_FOUND. - That the expected state admits the action and the reason matches. Otherwise,
422 MP_DIRECT_PURCHASE_ORDER_TRANSITION_INVALID. - That line matching and the company management chain allow the action, as in Purchase orders. Otherwise,
409 MP_DIRECT_PURCHASE_ORDER_GATE_LOCKED, with the reasons indetails.reasons. - That no other action is active on that order. If there is one,
409 MP_DIRECT_PURCHASE_ORDER_BUSY; retry when it ends.
In the portal, the extension reads the order again before acting: if the state is no longer the expected one, it does nothing. If the lease is lost during the action, the intent ends as uncertain: read the order with READ_PURCHASE_ORDER_STATE before repeating.
summary field | Required | Rule | Use |
|---|---|---|---|
po_code | No | Text matching ^[0-9]{1,9}-[0-9]{1,6}-[A-Z]{2}[0-9]{2}$ | Purchase order of the intent. |
po_status | No | Integer from 0 up to 99 | Number of the state observed in the portal. |
po_status_label | No | Text, 1 to 80 characters | Name of the observed state, as the portal shows it. |
po_observed_at | No | Text, 20 to 40 characters | Time of the reading. |
po_available_actions | No | Array, 0 to 5 | PURCHASE_ORDER_* actions the portal admits now, in READ_PURCHASE_ORDER_STATE. |
Deferred delivery
If the portal effect finished but your server did not receive the result after the retries, the extension keeps it sanitized on the Chrome executor (up to 10 results) and reports data_plane_delivery_ok: false to Masnet. In the next cycle it obtains a use = result_delivery token valid for 60 s and sends again to POST /masnet-gateway/v1/jobs/{jobRef}/result. Masnet issues it for 24 hours after the intent closes, while the integration, grant and executor remain active.
- Accept
use = result_deliveryonly on/result, with the sameIdempotency-Key. - When the window expires, the local result is deleted: reconcile with
GET https://daas.masnet.com/api/v1/integrations/data/mp-gateway/intents/{intentId}(summary.data_plane_delivery_ok).
Timeouts and uncertain
- Queued, an intent expires after 90 s with no effect.
- Running, the lease lasts 45 s and is renewed every 15 s. Pausing or revoking the integration, grant or executor cuts the lease at the next renewal.
- If the lease is lost without a result, an action with no portal effect ends as
failed; one with an effect ends asuncertainwithMP_DIRECT_LEASE_LOST. There is never an automatic retry: read the tender withREAD_SNAPSHOTbefore deciding. POST https://daas.masnet.com/api/v1/integrations/data/mp-gateway/intents/{intentId}/cancelstops the next steps; it does not undo what the portal already accepted.
Notifications
The domain webhooks (com.masnet.mp_gateway.intent_settled.v1 and com.masnet.mp_gateway.executor_status_changed.v1) are defined and planned: they are not emitted yet. Meanwhile, your system queries GET https://daas.masnet.com/api/v1/integrations/data/mp-gateway/intents/{intentId} with Prefer: wait and GET https://daas.masnet.com/api/v1/integrations/data/mp-gateway/executors.
Errors
Domain errors answer application/json with the envelope { "error": "MP_DIRECT_...", "detail": "...", "request_id": "...", "retry_after_seconds": 30 }; a 429 also carries Retry-After. Authentication, scopes and the per minute quota answer like the rest of the API, in application/problem+json (Errors). Extension codes arrive in error_code of the intent and of the result.
| Code | HTTP | Origin | Retry | Cause |
|---|---|---|---|---|
MP_DIRECT_ORIGIN_FORBIDDEN | 422 | Integrations API | No | The data_plane_origin breaks the policy: reserved domain, special-use name, literal IP, HTTP outside loopback, userinfo or path, or a transport mode the G-NET gate has not opened yet. |
MP_DIRECT_COMPANY_UNVERIFIED | 403 | Integrations API | No | The company does not have a verified tax ID (tin_status = verified) in Masnet. |
MP_DIRECT_ACTION_NOT_GRANTED | 403 | Integrations API | No | The action is not in allowed_actions of the current mp_gateway grant, or the credential belongs to a test integration and the action writes to Mercado Público. |
MP_DIRECT_EXECUTOR_OFFLINE | 503 | Integrations API | Yes | The chosen Chrome executor has not reported recent presence or is offline. |
MP_DIRECT_EXECUTOR_BUSY | 409 | Integrations API | Yes | The executor already has another active intent. |
MP_DIRECT_EXECUTOR_PAUSED | 409 | Integrations API | No | An administrator paused the executor. |
MP_DIRECT_EXECUTOR_REVOKED | 410 | Integrations API | No | The executor link was revoked. |
MP_DIRECT_PREPARE_REQUIRED | 409 | Integrations API | No | PUBLISH_BID requires a successful prepare_intent_id from the same executor and integration, with matching mp_bid_id and expected_observed_sha256. |
MP_DIRECT_IDEMPOTENCY_CONFLICT | 409 | Integrations API | No | client_request_id reused with a different body. |
MP_DIRECT_CAPABILITY_INVALID | 403 | Extension | No | The EdDSA capability failed signature, audience, validity, bindings or jti replay. |
MP_DIRECT_MANAGED_ORIGIN_MISMATCH | 403 | Extension | No | The policy requires require_managed_origin_pin and chrome.storage.managed does not match data_plane_origin. |
MP_DIRECT_SUPPLIER_MISMATCH | 403 | Extension | No | The tax ID of the active Mercado Público session in Chrome does not match the supplier_rut authorized by Masnet. |
MP_DIRECT_DATA_PLANE_UNREACHABLE | 502 | Your server | Yes | The extension could not reach the company data_plane_origin: DNS, TLS, CORS, Chrome local network permission or timeout. |
MP_DIRECT_REDIRECT_BLOCKED | 422 | Extension | No | The company server returned an HTTP 3xx redirect; blocked by redirect: error (SSRF defense). |
MP_DIRECT_MANIFEST_MISMATCH | 422 | Extension | No | The SHA-256 of the exact bytes the company server returned does not match the manifest_sha256 signed in the capability, or the manifest is for another tender. |
MP_DIRECT_DOCUMENT_MISMATCH | 422 | Extension | No | A file downloaded from the company server does not match the size_bytes or sha256 declared in the manifest. |
MP_DIRECT_SENSITIVE_DATA_REJECTED | 422 | Integrations API | No | The body sent to the control plane contained forbidden fields or credential, token or ViewState patterns. |
MP_DIRECT_LEASE_LOST | 410 | Extension | No | The intent lease was lost or revoked before the next effect on Mercado Público. |
MP_DIRECT_SESSION_REQUIRED | 409 | Integrations API | Yes | The executor has no active Mercado Público session. With SESSION_LOGIN granted, the system opens it with POST /api/v1/integrations/data/mp-gateway/session-flows; otherwise a person opens it in that Chrome. |
MP_DIRECT_DECLARANT_NOT_GRANTED | 403 | Extension | No | The manifest declarant is not in allowed_declarant_ruts of the grant. The sworn statement is not signed. |
MP_DIRECT_OBSERVED_MISMATCH | 409 | Extension | No | The Confirmation re-read before publishing does not match the evidence stored at preparation. Nothing is published. |
MP_DIRECT_SESSION_ACTIVE | 409 | Integrations API | No | The executor already has a Mercado Público session. A session flow does not overwrite it: use the current one or close it first with SESSION_LOGOUT. |
MP_DIRECT_SESSION_FLOW_LIMIT | 429 | Integrations API | Yes | 3 session flows in 15 minutes were reached on that executor, the account protection against portal lockout inherited from remote sign-in. Includes Retry-After. |
MP_DIRECT_SESSION_FLOW_STALE | 409 | Integrations API | Yes | expected_version, prompt_id or prompt_generation are no longer current. Read the flow again and answer the current prompt. |
MP_DIRECT_DELIVERY_CLOSED | 409 | Integrations API | No | The intent does not admit deferred delivery: it is not the executor's, it is not closed as succeeded or uncertain, its delivery already finished, the result_delivery_window_seconds window expired, or the integration, grant or executor are not active. |
MP_DIRECT_TENDER_BUSY | 409 | Integrations API | Yes | The company already has an active PREPARE_BID or PUBLISH_BID on that tender in this environment, in this lane or as a bid command of the human remote gateway. Retry when it ends. |
MP_DIRECT_ACTION_NOT_AVAILABLE | 409 | Integrations API | No | The purchase order action is not open in Masnet yet (the same list web-app uses). It is rejected when granted and when the intent is created. |
MP_DIRECT_PURCHASE_ORDER_NOT_FOUND | 404 | Integrations API | No | The purchase order does not exist or was not issued to the company verified tax ID. |
MP_DIRECT_PURCHASE_ORDER_TRANSITION_INVALID | 422 | Integrations API | No | The expected state does not admit the action, or the reason does not match the action. |
MP_DIRECT_PURCHASE_ORDER_GATE_LOCKED | 409 | Integrations API | No | Line matching or the company management chain is closed for this action. details.reasons carries the same reasons web-app shows. |
MP_DIRECT_PURCHASE_ORDER_BUSY | 409 | Integrations API | Yes | The company already has another active action on that purchase order in this environment, in this lane or in the human lane. |
Reference code
Data plane server in Node.js 18 or later, without dependencies: CORS, token verification against the JWKS and of use, manifest by exact bytes, attachments with their hash, progress and an idempotent result with the observed digest recomputed. Tested against test Ed25519 tokens.
// Servidor del plano de datos del gateway de Mercado Público (mp-gateway.direct-data-plane.v1, sección data_plane).
// Node.js 18 o superior, sin dependencias. Atiende los cinco endpoints bajo /masnet-gateway/v1 que llama la extensión
// de Masnet desde el Chrome ejecutor de la empresa. Masnet nunca llama a este servidor.
import { createHash, createPublicKey, timingSafeEqual, verify } from 'node:crypto'
export const BASE_PATH = '/masnet-gateway/v1'
export const EXTENSION_ORIGIN = 'chrome-extension://icghfhpbiebbbocbheaieofjadfnlmgg'
export const TOKEN_TYPE = 'mp-gateway-dataplane+jwt'
export const ISSUERS = ['https://daas.masnet.com', 'https://dev-daas.masnet.com']
const CLOCK_SKEW_SECONDS = 5
const MAX_BODY_BYTES = 4 * 1024 * 1024
const CLAIMS = ['v', 'iss', 'aud', 'sub', 'jti', 'iat', 'exp', 'company_id', 'integration_id', 'executor_id', 'intent_id', 'action', 'job_ref', 'use']
export const sha256Hex = (bytes) => createHash('sha256').update(bytes).digest('hex')
/** Cabeceras CORS de cada respuesta, también de los errores y del preflight. Nunca `*` ni Allow-Credentials. */
export function corsHeaders(extensionOrigin = EXTENSION_ORIGIN) {
return {
'Access-Control-Allow-Origin': extensionOrigin,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Authorization, Content-Type, X-Masnet-Intent-Id, X-Masnet-Device-Id, X-Masnet-Job-Ref, Idempotency-Key',
'Access-Control-Expose-Headers': 'X-Document-Sha256, Content-Type, Content-Length, Retry-After',
Vary: 'Origin',
'Cache-Control': 'no-store',
}
}
/**
* Claves públicas del token, desde GET {iss}/api/v1/integrations/public/mp-gateway/jwks.json. Se guardan por `kid`; un `kid`
* desconocido vuelve a leer el JWKS como máximo una vez por minuto, porque Masnet rota las claves.
*/
export function createJwksCache(issuer, fetchImpl = fetch) {
const keys = new Map()
let fetchedAt = 0
return async function keyFor(kid) {
if (!keys.has(kid) && Date.now() - fetchedAt > 60_000) {
fetchedAt = Date.now()
const response = await fetchImpl(`${issuer}/api/v1/integrations/public/mp-gateway/jwks.json`, { redirect: 'error' })
if (!response.ok) throw new Error(`JWKS ${response.status}`)
const { keys: list } = await response.json()
keys.clear()
for (const jwk of list) {
if (jwk.kty === 'OKP' && jwk.crv === 'Ed25519' && jwk.alg === 'EdDSA' && jwk.use === 'sig') keys.set(jwk.kid, createPublicKey({ key: jwk, format: 'jwk' }))
}
}
return keys.get(kid) ?? null
}
}
const json = (part) => JSON.parse(Buffer.from(part, 'base64url').toString('utf8'))
/**
* Verifica el token de la extensión. Devuelve sus claims o lanza un error. `expected`:
* - `origin`: el data_plane_origin exacto de su servidor (sin barra final), que es la audiencia.
* - `integrationId`, `companyId` y `executorIds`: los de su integración.
* - `jobRef`: el de la ruta. `intentIdFor(jobRef)`: el intent_id que recibió al crear el intent de ese job_ref.
* - `route`: 'result' para POST /jobs/{jobRef}/result; cualquier otro valor para las demás rutas del job.
*/
export async function verifyDataPlaneToken(authorization, keyFor, expected, now = Math.floor(Date.now() / 1000)) {
const match = /^Bearer ([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]+)$/.exec(authorization ?? '')
if (!match) throw new Error('sin token')
const [, headerPart, payloadPart, signaturePart] = match
const header = json(headerPart)
if (header.alg !== 'EdDSA' || header.typ !== TOKEN_TYPE || typeof header.kid !== 'string') throw new Error('cabecera')
const key = await keyFor(header.kid)
if (!key) throw new Error('kid desconocido')
if (!verify(null, Buffer.from(`${headerPart}.${payloadPart}`), key, Buffer.from(signaturePart, 'base64url'))) throw new Error('firma')
const claims = json(payloadPart)
if (Object.keys(claims).some((k) => !CLAIMS.includes(k) && k !== 'tender_code') || CLAIMS.some((k) => !(k in claims))) throw new Error('claims')
if (claims.v !== 1 || !ISSUERS.includes(claims.iss) || claims.aud !== expected.origin) throw new Error('iss o aud')
if (claims.exp + CLOCK_SKEW_SECONDS < now || claims.iat - CLOCK_SKEW_SECONDS > now) throw new Error('vigencia')
if (claims.sub !== `integration:${expected.integrationId}` || claims.integration_id !== expected.integrationId) throw new Error('integración')
if (claims.company_id !== expected.companyId || !expected.executorIds.includes(claims.executor_id)) throw new Error('empresa o ejecutor')
if (claims.job_ref !== expected.jobRef || claims.intent_id !== await expected.intentIdFor(claims.job_ref)) throw new Error('job o intent')
if (claims.use === 'result_delivery' ? expected.route !== 'result' : claims.use !== 'job') throw new Error('use')
return claims
}
/** JSON canónico: sin espacios y con las claves de cada objeto ordenadas por unidad de código UTF-16. */
export function canonicalJson(value) {
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`
if (value && typeof value === 'object') return `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`).join(',')}}`
return JSON.stringify(value)
}
/** Digest de la evidencia observada (BidObservedMaterial versión 1): el mismo que Masnet guarda como observed_sha256. */
export const observedSha256 = (observed) => sha256Hex(Buffer.from(canonicalJson(observed), 'utf8'))
/**
* Manejador http(s) de Node. `store` es su sistema:
* - `job(jobRef)`: { intentId, manifest (Buffer con los bytes exactos cuyo SHA-256 envió en el intent), documents: Map(docId -> Buffer) } o null.
* - `saveProgress(jobRef, body)` y `saveResult(jobRef, body, { observedDigestOk })`: guardan; `saveResult` devuelve true si el intent
* ya tenía resultado (la extensión reintenta con la misma Idempotency-Key).
*/
export function createDataPlaneHandler({ origin, integrationId, companyId, executorIds, keyFor, store, extensionOrigin = EXTENSION_ORIGIN }) {
const cors = corsHeaders(extensionOrigin)
const send = (res, status, body, headers = {}) => {
res.writeHead(status, { ...cors, ...headers })
res.end(body)
}
const sendJson = (res, status, value) => send(res, status, JSON.stringify(value), { 'Content-Type': 'application/json' })
const readBody = (req) => new Promise((resolve, reject) => {
const chunks = []
let size = 0
req.on('data', (chunk) => {
size += chunk.length
if (size > MAX_BODY_BYTES) { reject(new Error('cuerpo demasiado grande')); req.destroy() } else chunks.push(chunk)
})
req.on('end', () => resolve(Buffer.concat(chunks)))
req.on('error', reject)
})
return async function handle(req, res) {
const url = new URL(req.url, 'http://local')
if (req.method === 'OPTIONS') return send(res, 204, '')
if (req.method === 'GET' && url.pathname === `${BASE_PATH}/health`) {
return sendJson(res, 200, { status: 'ok', protocol_version: 'mp-gateway-direct.v1', server_time: new Date().toISOString() })
}
const route = new RegExp(`^${BASE_PATH}/jobs/([A-Za-z0-9][A-Za-z0-9._:-]{0,127})/(manifest|progress|result|documents/([A-Za-z0-9][A-Za-z0-9._:-]{0,127}))$`).exec(url.pathname)
if (!route) return send(res, 404, '')
const [, jobRef, kind, docId] = route
const job = await store.job(jobRef)
if (!job) return send(res, 404, '')
try {
await verifyDataPlaneToken(req.headers.authorization, keyFor, {
origin, integrationId, companyId, executorIds, jobRef, intentIdFor: async () => job.intentId, route: kind === 'result' ? 'result' : 'job',
})
} catch {
return send(res, 401, '')
}
if (req.method === 'GET' && kind === 'manifest') {
return send(res, 200, job.manifest, { 'Content-Type': 'application/json', 'Content-Length': String(job.manifest.length) })
}
if (req.method === 'GET' && docId) {
const bytes = job.documents.get(docId)
if (!bytes) return send(res, 404, '')
return send(res, 200, bytes, { 'Content-Type': 'application/octet-stream', 'Content-Length': String(bytes.length), 'X-Document-Sha256': sha256Hex(bytes) })
}
if (req.method === 'POST' && kind === 'progress') {
await store.saveProgress(jobRef, JSON.parse((await readBody(req)).toString('utf8')))
return send(res, 204, '')
}
if (req.method === 'POST' && kind === 'result') {
const key = Buffer.from(String(req.headers['idempotency-key'] ?? ''))
const intent = Buffer.from(job.intentId)
if (key.length !== intent.length || !timingSafeEqual(key, intent)) return send(res, 400, '')
const body = JSON.parse((await readBody(req)).toString('utf8'))
if (body.intent_id !== job.intentId) return send(res, 400, '')
// La evidencia es lo que el portal muestra. Se acusa recibo igual; su sistema decide con `observedDigestOk` y comparando
// cada línea con su propia oferta antes de pedir PUBLISH_BID.
const observedDigestOk = body.observed_bid ? observedSha256(body.observed_bid.observed) === body.observed_bid.observed_sha256 : null
const replayed = await store.saveResult(jobRef, body, { observedDigestOk })
return sendJson(res, 200, { received: true, intent_id: job.intentId, replayed })
}
return send(res, 405, '')
}
}Token verification and evidence digest in Python 3.9 or later with cryptography.
# Verificación del token del plano de datos y digest de la evidencia observada (mp-gateway.direct-data-plane.v1).
# Python 3.9 o superior con el paquete cryptography (pip install cryptography).
import base64
import hashlib
import json
import time
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
TOKEN_TYPE = "mp-gateway-dataplane+jwt"
ISSUERS = ("https://daas.masnet.com", "https://dev-daas.masnet.com")
CLOCK_SKEW_SECONDS = 5
CLAIMS = {"v", "iss", "aud", "sub", "jti", "iat", "exp", "company_id", "integration_id", "executor_id", "intent_id", "action", "job_ref", "use"}
def b64u_decode(text):
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
def keys_from_jwks(jwks):
"""Claves públicas por kid desde GET {iss}/api/v1/integrations/public/mp-gateway/jwks.json."""
return {
k["kid"]: Ed25519PublicKey.from_public_bytes(b64u_decode(k["x"]))
for k in jwks["keys"]
if k.get("kty") == "OKP" and k.get("crv") == "Ed25519" and k.get("alg") == "EdDSA" and k.get("use") == "sig"
}
def verify_data_plane_token(authorization, keys, origin, integration_id, company_id, executor_ids, job_ref, intent_id, route, now=None):
"""Devuelve los claims o lanza ValueError. route es "result" para POST /jobs/{jobRef}/result y "job" para las demás rutas."""
now = int(time.time()) if now is None else now
if not authorization or not authorization.startswith("Bearer "):
raise ValueError("sin token")
parts = authorization[len("Bearer "):].split(".")
if len(parts) != 3:
raise ValueError("formato")
header = json.loads(b64u_decode(parts[0]))
if header.get("alg") != "EdDSA" or header.get("typ") != TOKEN_TYPE:
raise ValueError("cabecera")
key = keys.get(header.get("kid"))
if key is None:
raise ValueError("kid desconocido: vuelva a leer el JWKS")
try:
key.verify(b64u_decode(parts[2]), f"{parts[0]}.{parts[1]}".encode("ascii"))
except InvalidSignature:
raise ValueError("firma")
claims = json.loads(b64u_decode(parts[1]))
if not CLAIMS.issubset(claims) or not set(claims).issubset(CLAIMS | {"tender_code"}):
raise ValueError("claims")
if claims["v"] != 1 or claims["iss"] not in ISSUERS or claims["aud"] != origin:
raise ValueError("iss o aud")
if claims["exp"] + CLOCK_SKEW_SECONDS < now or claims["iat"] - CLOCK_SKEW_SECONDS > now:
raise ValueError("vigencia")
if claims["sub"] != f"integration:{integration_id}" or claims["integration_id"] != integration_id:
raise ValueError("integración")
if claims["company_id"] != company_id or claims["executor_id"] not in executor_ids:
raise ValueError("empresa o ejecutor")
if claims["job_ref"] != job_ref or claims["intent_id"] != intent_id:
raise ValueError("job o intent")
if claims["use"] == "result_delivery":
if route != "result":
raise ValueError("use")
elif claims["use"] != "job":
raise ValueError("use")
return claims
def canonical_json(value):
"""JSON sin espacios, claves ordenadas por unidad de código UTF-16 (en BidObservedMaterial todas son ASCII)."""
return json.dumps(value, separators=(",", ":"), sort_keys=True, ensure_ascii=False)
def observed_sha256(observed):
"""Digest de BidObservedMaterial versión 1: el mismo valor que Masnet guarda como observed_sha256."""
return hashlib.sha256(canonical_json(observed).encode("utf-8")).hexdigest()